<template>
    <div class="customer-container">
        <el-tabs v-model="activeTab" @tab-click="handleTabChange" class="record-tabs">
            <el-tab-pane label="客户列表" name="0"></el-tab-pane>
        </el-tabs>

        <el-card class="filter-card">
            <el-form :inline="true" :model="queryParams" class="filter-form">
                <el-form-item label="日期范围">
                    <el-date-picker
                        v-model="dateRange"
                        type="daterange"
                        range-separator="至"
                        start-placeholder="开始日期"
                        end-placeholder="结束日期"
                    />
                </el-form-item>
                <!-- <el-form-item label="招商员" prop="businessDeveloper">
                    <el-input
                        v-model="queryParams.businessDeveloper"
                        placeholder="请输入招商员"
                        clearable                style="width: 180px"
                        @keyup.enter="handleQuery"
                    />
                </el-form-item> -->
                <el-form-item label="招商员">
                    <el-select
                        v-model="queryParams.businessDeveloper"
                        placeholder="请输入招商员"
                        clearable                style="width: 220px"
                        filterable
                        :loading="dropdownLoading"
                        multiple
                    >
                        <el-option
                            v-for="item in businessDevelopers"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                            
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="意向项目">
                    <el-select
                        v-model="queryParams.intentionProject"
                        placeholder="请选择意向项目"
                        clearable                style="width: 220px"
                        @focus="handleSelectFocus('intentionProject')"
                        @change="fetchBusinessDevelopers"
                        filterable
                        :loading="dropdownLoading"
                        multiple
                    >
                        <el-option
                            v-for="item in dropdownData.intentionProject"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="联系方式" prop="contactPhone">
                    <el-input
                        v-model="queryParams.contactPhone"
                        placeholder="请输入联系方式"
                        clearable                style="width: 180px"
                        @keyup.enter="handleQuery"
                    />
                </el-form-item>
                <el-form-item label="客户类型" prop="investmentTarget">
                    <el-cascader
                        v-model="queryParams.investmentTargetValue"
                        :options="customerTypeOptions"
                        :props="cascaderProps"
                        placeholder="请选择客户类型"    style="width: 100%"
                        clearable
                        @change="handleCustomerTypeChange"
                    />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
                    <el-button icon="Refresh" @click="resetQuery">重置</el-button>
                    <el-button type="success" icon="Plus" @click="openAddDialog">新增</el-button>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 列表显示区域 -->
        <el-card class="list-card">
            <el-table v-loading="loading" :data="customerList" style="width: 100%" border>
                <el-table-column label="序号" width="60">
                    <template #default="{ $index }">
                        {{ ($index + 1) + (queryParams.pageNum - 1) * queryParams.pageSize }}
                    </template>
                </el-table-column>
                <el-table-column
                    prop="department"
                    label="部门"
                    width="90"
                    show-overflow-tooltip
                />
                <el-table-column prop="businessDeveloper" label="招商员" min-width="70"/>
                <el-table-column prop="companyName" label="企业名称" min-width="240"/>
                <el-table-column prop="customerIntentionLevel" label="客户意向等级" min-width="90">
                    <template #default="{ row }">
                        <el-tag
                            :type="getTagType(row.customerIntentionLevel)"
                            size="small"
                            class="intention-level-tag"
                        >
                            {{
                                row.customerIntentionLevel == 4 ? 'A级' :
                                    row.customerIntentionLevel == 3 ? 'B级' :
                                        row.customerIntentionLevel == 2 ? 'C级' :
                                            row.customerIntentionLevel == 1 ? 'D级' : ''
                            }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="investmentTarget" label="客户类型" min-width="90"/>
                <el-table-column prop="category" label="渠道分类" min-width="90"/>
                <el-table-column prop="reportTime" label="报备时间" min-width="90">
                    <template #default="{ row }">
                        {{ row.reportTime ? row.reportTime.split(' ')[0] : '-' }}
                    </template>
                </el-table-column>
                <el-table-column prop="intentionProject" label="意向项目" min-width="90"/>
                <el-table-column prop="customerSource" label="客户来源" min-width="120"/>
                <el-table-column prop="customerSourceDesc" label="客户来源说明" min-width="140">
                    <template #default="{ row }">
                        <template v-if="row.customerSourceDesc">
                            <el-tooltip :content="row.customerSourceDesc" placement="top">
                                <span class="ellipsis-cell">{{ row.customerSourceDesc }}</span>
                            </el-tooltip>
                        </template>
                        <span v-else>-</span>
                    </template>
                </el-table-column>
                <el-table-column
                    prop="customerCategory"
                    label="客户状态"
                    min-width="90"
                    width="90"
                />
                <el-table-column prop="employeeCount" label="员工人数" min-width="90"/>
                <el-table-column prop="mainBusiness" label="主营业务" min-width="140">
                    <template #default="{ row }">
                        <template v-if="row.mainBusiness">
                            <el-tooltip :content="row.mainBusiness" placement="top">
                                <span class="ellipsis-cell">{{ row.mainBusiness }}</span>
                            </el-tooltip>
                        </template>
                        <span v-else>-</span>
                    </template>
                </el-table-column>
                <el-table-column prop="requirementType" label="企业需求" min-width="90"/>
                <el-table-column prop="requirementDesc" label="企业需求描述" min-width="110" show-overflow-tooltip/>
                <el-table-column prop="basicInfoRequired" label="基本信息必填" min-width="110">
                    <template #default="{ row }">
                        <el-tag
                            :type="row.basicInfoRequired === 1 ? 'success' : 'info'"
                            size="small"
                            class="status-tag"
                        >
                            {{ row.basicInfoRequired === 0 ? '未完善' : '已完善' }}
                        </el-tag>
                    </template>
                </el-table-column>

                <el-table-column prop="requirementRequired" label="需求必填" min-width="100">
                    <template #default="{ row }">
                        <el-tag
                            :type="row.requirementRequired === 1 ? 'success' : 'info'"
                            size="small"
                            class="status-tag"
                        >
                            {{ row.requirementRequired === 0 ? '未完善' : '已完善' }}
                        </el-tag>
                    </template>
                </el-table-column>

                <el-table-column prop="contactInfoRequired" label="联系人信息必填" min-width="130">
                    <template #default="{ row }">
                        <el-tag
                            :type="row.contactInfoRequired === 1 ? 'success' : 'info'"
                            size="small"
                            class="status-tag"
                        >
                            {{ row.contactInfoRequired === 0 ? '未完善' : '已完善' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="investmentPurpose" label="招商目的" min-width="90"/>
                <el-table-column prop="industry" label="所属行业" min-width="100"/>
                <el-table-column prop="checkInType" label="入驻形态" min-width="90"/>
                <el-table-column prop="enterpriseQualification" label="企业资质" min-width="90"/>
                <el-table-column prop="enterpriseProvince" label="企业所在省" min-width="80"/>
                <el-table-column prop="enterpriseCity" label="企业所在市" min-width="80"/>
                <el-table-column prop="enterpriseDistrict" label="企业所在区" min-width="80"/>
                <el-table-column prop="resourceCapability" label="资源能力" min-width="90"/>
                <el-table-column prop="channelLevel" label="渠道级别" min-width="90"/>
                <el-table-column prop="isSigned" label="是否签约" min-width="90"/>

                <el-table-column prop="attribution" label="归属部门" min-width="90"/>
                <el-table-column label="操作" min-width="130" fixed="right">
                    <template #default="{ row }">
                        <el-button-group>
                            <el-button
                                type="primary"
                                size="small"
                                @click="handleInfoManage(row)"
                                class="operation-button"
                            >
                                编辑
                            </el-button>
                            <el-button
                                type="primary"
                                size="small"
                                @click="openDrawer(row)"
                                class="operation-button"
                            >
                                更多
                            </el-button>
                        </el-button-group>
                    </template>
                </el-table-column>
            </el-table>
            <pagination
                v-show="total > 0"
                :total="total"
                v-model:page="queryParams.pageNum"
                v-model:limit="queryParams.pageSize"
                @pagination="getList"
            />
        </el-card>

        <!-- 快捷操作抽屉 -->
        <el-drawer
            v-model="drawerVisible"
            title="快捷操作"
            :before-close="handleClose"
            size="60%"
            direction="rtl"
            :show-close="true"
            :destroy-on-close="true"
        >
            <div class="drawer-content">
                <!-- 企业信息头部 -->
                <div class="company-header">
                    <h3>目标企业：{{ currentCompany.companyName }}</h3>
                </div>

                <!-- 企业基本信息 - 优化为两列布局 -->
                <div class="company-info">
                    <div class="info-item">
                        <span class="label">客户名称：</span>
                        <span class="value">{{ currentCompany.companyName || '-' }}</span>
                    </div>
                    <div class="info-item">
                        <span class="label">意向项目：</span>
                        <span class="value">{{ currentCompany.intentionProject || '-' }}</span>
                    </div>
                    <div class="info-item">
                        <span class="label">客户意向等级：</span>
                        <span class="value">
            {{
                                currentCompany.customerIntentionLevel == 4 ? 'A级 (已缴纳意向金)' :
                                    currentCompany.customerIntentionLevel == 3 ? 'B级 (1个月内可签约)' :
                                        currentCompany.customerIntentionLevel == 2 ? 'C级 (3个月内需持续培育)' :
                                            currentCompany.customerIntentionLevel == 1 ? 'D级 (明确表示无意向)' : ''

                            }}
        </span>
                    </div>
                    <div class="info-item">
                        <span class="label">拓客渠道来源：</span>
                        <span class="value">{{ currentCompany.customerSource || '-' }}</span>
                    </div>
                    <div class="info-item">
                        <span class="label">客户入驻形态：</span>
                        <span class="value">{{ currentCompany.checkInType || '-' }}</span>
                    </div>
                    <div class="info-item">
                        <span class="label">企业所在区域：</span>
                        <span class="value">{{ currentCompany.enterpriseProvince || '-' }} {{ currentCompany.enterpriseCity || '' }} {{ currentCompany.enterpriseDistrict || '' }}</span>
                    </div>
                    <div class="info-item">
                        <span class="label">上年税收(万元)：</span>
                        <span class="value">{{ currentCompany.annualTax || '-' }}</span>
                    </div>
                    <div class="info-item">
                        <span class="label">所属行业：</span>
                        <span class="value">{{ currentCompany.industry || '-' }}</span>
                    </div>
                    <div class="info-item">
                        <span class="label">招商目的：</span>
                        <span class="value">{{ currentCompany.investmentPurpose || '-' }}</span>
                    </div>
                    <div class="info-item">
                        <span class="label">资源能力：</span>
                        <span class="value">{{ currentCompany.resourceCapability || '-' }}</span>
                    </div>
                    <div class="info-item">
                        <span class="label">企业资质：</span>
                        <span class="value">{{ currentCompany.enterpriseQualification || '-' }}</span>
                    </div>
                    <div class="info-item">
                        <span class="label">企业人数：</span>
                        <span class="value">{{ currentCompany.employeeCount || '-' }}</span>
                    </div>
                    <div class="info-item">
                        <span class="label">主营业务：</span>
                        <span class="value">{{ currentCompany.mainBusiness || '-' }}</span>
                    </div>
                    <div class="info-item">
                        <span class="label">主要关注点：</span>
                        <span class="value">{{ currentCompany.focusPoint || '-' }}</span>
                    </div>
                </div>

                <!-- 操作列表 -->
                <div class="operation-list">
                    <div class="list-title">
                        <span>操作列表</span>
                        <el-button
                            type="text"
                            icon="Refresh"
                            circle
                            size="small"
                            @click="refreshData"
                        />
                    </div>

                    <div class="operation-group">
                        <div class="group-title">信息管理</div>
                        <div class="operation-buttons">
                            <!-- <el-button type="primary" @click="handleInfoManage">基本信息维护</el-button> -->
                            <el-button type="primary" @click="handleContactManage">联系人维护</el-button>
                            <el-button type="primary" @click="handleReassign">重新分配跟进人员</el-button>
                        </div>
                    </div>

                    <div class="operation-group">
                        <div class="group-title">跟进管理</div>
                        <div class="operation-buttons">
                            <el-button type="primary" @click="handleAddFollowUp">添加跟进记录</el-button>
                            <!--                            <el-button type="info" @click="handleReportDifficulty">招商难点提报</el-button>-->
                            <el-button type="warning" @click="handleAbandon" v-if="!currentCompany.customerId || !currentCompany.customerId.startsWith('qd')">退回公海池</el-button>
                        </div>
                    </div>

                    <div class="operation-group" v-if="!currentCompany.customerId || !currentCompany.customerId.startsWith('qd')">
                        <div class="group-title">证照办理</div>
                        <div class="operation-buttons">
                            <el-button type="primary" @click="openReportDialog">新注册</el-button>
                            <el-button type="primary" @click="handleRelocation">迁址</el-button>
                        </div>
                    </div>
                </div>

                <!-- 客户需求模块 -->
                <div class="operation-group" v-if="!currentCompany.customerId || !currentCompany.customerId.startsWith('qd')">
                    <div class="group-title">客户需求</div>
                    <div class="operation-buttons">
                        <!-- 添加客户需求下拉框 -->
                        <el-dropdown @command="handleAddRequirementCommand">
            <span class="el-dropdown-link">
                <el-button type="text" size="small">
                    添加客户需求
                </el-button>
            </span>
                            <template #dropdown>
                                <el-dropdown-menu>
                                    <el-dropdown-item command="carrier">载体需求</el-dropdown-item>
                                    <el-dropdown-item command="policy">政策需求</el-dropdown-item>
                                    <el-dropdown-item command="research">研发需求</el-dropdown-item>
                                    <el-dropdown-item command="tech">科技申报</el-dropdown-item>
                                    <el-dropdown-item command="talent">人才申报</el-dropdown-item>
                                    <el-dropdown-item command="commission">佣金费用</el-dropdown-item>
                                    <el-dropdown-item command="overseas">出海需求</el-dropdown-item>
                                    <el-dropdown-item command="university">院校合作</el-dropdown-item>
                                    <el-dropdown-item command="market">市场对接</el-dropdown-item>
                                    <el-dropdown-item command="finance">融资需求</el-dropdown-item>
                                    <el-dropdown-item command="health">健康需求</el-dropdown-item>
                                </el-dropdown-menu>
                            </template>
                        </el-dropdown>
                    </div>

                    <!-- 客户需求展示区域 -->
                    <div class="requirement-container">
                        <div v-if="customerRequirements.length === 0 && !editingForm" class="empty-tip">
                            暂无客户需求
                        </div>

                        <!-- 编辑表单 - 动态显示不同需求类型的表单 -->
                        <div v-if="editingForm" class="edit-form-container">
                            <el-form :model="editForm" label-width="120px" class="edit-form">
                                <el-form-item label="需求类型">
                                    <el-input v-model="editForm.requirementType" disabled />
                                </el-form-item>
                                <el-form-item label="意向项目">
                                    <el-select
                                        v-model="editForm.intentionProject"
                                        placeholder="请选择意向项目"
                                        clearable
                                        @focus="handleSelectFocus('intentionProject')"
                                        filterable
                                        :loading="dropdownLoading"
                                    >
                                        <el-option
                                            v-for="item in dropdownData.intentionProject"
                                            :key="item.value"
                                            :label="item.label"
                                            :value="item.value"
                                        />
                                    </el-select>
                                </el-form-item>

                                <!-- 载体需求表单 -->
                                <div v-if="currentRequirementType === 'carrier'">
                                    <el-form-item label="需求面积" prop="requiredArea">
                                        <el-select
                                            v-model="editForm.requiredArea"
                                            placeholder="请选择需求面积"
                                            style="width: 100%"
                                            clearable
                                        >
                                            <el-option label="100㎡以下" value="100以下"/>
                                            <el-option label="100-200㎡" value="100-200"/>
                                            <el-option label="200-300㎡" value="200-300"/>
                                            <el-option label="300-500㎡" value="300-500"/>
                                            <el-option label="500-1000㎡" value="500-1000"/>
                                            <el-option label="1000㎡以上" value="1000以上"/>
                                        </el-select>
                                    </el-form-item>
                                    <el-form-item label="期盼单价">
                                        <el-input v-model.number="editForm.expectedPrice" placeholder="请输入期盼单价" />
                                    </el-form-item>
                                    <el-form-item label="找房原因" prop="requirementReason">
                                        <el-select
                                            v-model="editForm.requirementReason"
                                            placeholder="请选择找房原因"
                                            style="width: 100%"
                                            clearable
                                        >
                                            <el-option label="新开公司" value="新开公司"/>
                                            <el-option label="公司迁徙" value="公司迁徙"/>
                                            <el-option label="公司扩张" value="公司扩张"/>
                                            <el-option label="投资" value="投资"/>
                                            <el-option label="其他" value="其他"/>
                                        </el-select>
                                    </el-form-item>
                                    <el-form-item label="房屋用途" prop="requirementPurpose">
                                        <el-select
                                            v-model="editForm.requirementPurpose"
                                            placeholder="请选择房屋用途"
                                            style="width: 100%"
                                            clearable
                                        >
                                            <el-option label="办公" value="办公"/>
                                            <el-option label="生产" value="生产"/>
                                            <el-option label="研发" value="研发"/>
                                            <el-option label="注册" value="注册"/>
                                            <el-option label="库房" value="库房"/>
                                            <el-option label="其他" value="其他"/>
                                        </el-select>
                                    </el-form-item>
                                </div>

                                <!-- 政策需求表单 -->
                                <div v-if="currentRequirementType === 'policy'">
                                    <el-form-item label="预计税收">
                                        <el-input
                                            v-model.number="editForm.estimatedTax"
                                            placeholder="请输入预计税收"
                                            style="width: 100%"
                                        >
                                            <template #append>元/每平米/每月</template>
                                        </el-input>
                                    </el-form-item>
                                </div>

                                <!-- 其他需求类型表单（科技申报、研发需求等） -->
                                <div v-if="currentRequirementType !== 'carrier' && currentRequirementType !== 'policy'">
                                    <el-form-item label="需求描述">
                                        <el-input
                                            v-model="editForm.requirementDesc"
                                            type="textarea"
                                            :rows="3"
                                            placeholder="请输入需求描述"
                                        />
                                    </el-form-item>
                                </div>

                                <!-- 需求备注（所有类型都有） -->
                                <el-form-item v-if="currentRequirementType === 'carrier' || currentRequirementType === 'policy'" label="需求备注">
                                    <el-input v-model="editForm.requirementDesc" type="textarea" :rows="3" placeholder="请输入需求备注" />
                                </el-form-item>
                            </el-form>

                            <div class="form-actions">
                                <el-button @click="cancelEdit">取消</el-button>
                                <el-button type="primary" @click="saveEdit">保存</el-button>
                            </div>
                        </div>

                        <!-- 已保存的需求列表 -->
                        <div v-for="(requirement, index) in customerRequirements" :key="index" class="requirement-item">
                            <div class="requirement-header">
                                <div class="requirement-type">
                                    <span>{{ requirement.requirementType }}</span>
                                    <el-button type="text" @click="editRequirement(index)">
                                        <el-icon><Edit /></el-icon>
                                    </el-button>
                                </div>
                            </div>

                            <div class="requirement-content">
                                <div class="requirement-row">
                                    <span class="label">需求类型：</span>
                                    <span class="value">{{ requirement.requirementType }}</span>
                                </div>
                                <div class="requirement-row">
                                    <span class="label">意向项目：</span>
                                    <span class="value">{{ requirement.intentionProject }}</span>
                                </div>

                                <!-- 载体需求展示 -->
                                <div v-if="requirement.requirementType === '载体需求'">
                                    <div class="requirement-row">
                                        <span class="label">需求面积：</span>
                                        <span class="value">{{ requirement.requiredArea }}</span>
                                    </div>
                                    <div class="requirement-row">
                                        <span class="label">期盼单价：</span>
                                        <span class="value">{{ requirement.expectedPrice }}</span>
                                    </div>
                                    <div class="requirement-row">
                                        <span class="label">找房原因：</span>
                                        <span class="value">{{ requirement.requirementReason }}</span>
                                    </div>
                                    <div class="requirement-row">
                                        <span class="label">房屋用途：</span>
                                        <span class="value">{{ requirement.requirementPurpose }}</span>
                                    </div>
                                </div>

                                <!-- 政策需求展示 -->
                                <div v-if="requirement.requirementType === '政策需求'">
                                    <div class="requirement-row">
                                        <span class="label">预计税收：</span>
                                        <span class="value">{{ requirement.estimatedTax }} 元/每平米/每月</span>
                                    </div>
                                </div>

                                <!-- 其他需求展示 -->
                                <div v-if="requirement.requirementType !== '载体需求' && requirement.requirementType !== '政策需求'">
                                    <div class="requirement-row">
                                        <span class="label">需求描述：</span>
                                        <span class="value">{{ requirement.requirementDesc || '暂无' }}</span>
                                    </div>
                                </div>

                                <!-- 需求备注展示 -->
                                <div v-if="requirement.requirementDesc && (requirement.requirementType === '载体需求' || requirement.requirementType === '政策需求')">
                                    <div class="requirement-row">
                                        <span class="label">需求备注：</span>
                                        <span class="value">{{ requirement.requirementDesc }}</span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- 相关跟进表格 -->
                <div class="operation-group">
                    <div class="group-title">相关跟进</div>
                    <div class="operation-buttons">
                        <!-- 这里可以添加其他操作按钮 -->
                    </div>

                    <!-- 相关跟进表格 -->
                    <div class="follow-table-container">
                        <el-table
                            :data="followList" style="width: 100%"
                            border
                            :header-cell-style="{ background: '#f7f9fa', color: '#444' }"
                            :cell-style="{ padding: '8px' }"
                        >
                            <el-table-column prop="investmentStaff" label="招商员" show-overflow-tooltip/>
                            <el-table-column prop="investmentTarget" label="客户类型" show-overflow-tooltip/>
                            <el-table-column prop="followUpTime" label="跟进时间" show-overflow-tooltip/>
                            <el-table-column prop="followUpType" label="跟进方式" show-overflow-tooltip/>
                            <el-table-column prop="followUpContent" label="跟进内容" show-overflow-tooltip/>
                            <el-table-column prop="followUpCount" label="总跟进次数" show-overflow-tooltip/>
                            <el-table-column prop="customerSource" label="客户来源" show-overflow-tooltip/>
                            <el-table-column prop="customerProgress" label="招商阶段" show-overflow-tooltip/>
                            <el-table-column prop="accompanyStaff" label="陪访人员" show-overflow-tooltip/>
                            <el-table-column prop="companyName" label="企业名称" show-overflow-tooltip/>
                            <el-table-column prop="id" label="操作" min-width="80">
                                <template #default="{ row }">
                                    <el-button type="text" @click="viewFollowDetail(row)">
                                        查看
                                    </el-button>
                                </template>
                            </el-table-column>
                        </el-table>

                        <!-- 分页组件 -->
                        <pagination
                            v-show="followTotal > 0"
                            :total="followTotal"
                            v-model:page="followParams.pageNum"
                            v-model:limit="followParams.pageSize"
                            @pagination="getFollowList"
                        />
                    </div>
                </div>
            </div>
        </el-drawer>

        <!-- 基本信息维护弹窗 -->
        <!-- 基本信息维护弹窗 -->
        <el-dialog
            v-model="infoDialogVisible"
            title="基本信息维护"
            width="600px"
            :before-close="handleInfoDialogClose"
        >
            <el-form
                ref="infoFormRef"
                :model="infoForm"
                :rules="infoRules"
                label-width="120px"
                class="info-form"
            >
                <el-form-item label="客户名称" prop="companyName">
                    <el-input v-model="infoForm.companyName" placeholder="请输入客户名称" clearable/>
                </el-form-item>

                <el-form-item label="联系人" prop="contactPerson">
                    <el-input
                        v-model="infoForm.contactPerson"
                        placeholder="请输入联系人"
                        clearable
                        disabled
                    />
                </el-form-item>

                <el-form-item label="联系方式" prop="contactPhone">
                    <el-input v-model="infoForm.contactPhone"
                              placeholder="请输入联系方式"
                              clearable
                              disabled
                    />
                </el-form-item>

                <!-- 企业客户显示的字段 (customerId不以"qd"开头) -->
                <template v-if="!currentCompany.customerId || !currentCompany.customerId.startsWith('qd')">
                    <el-form-item label="意向项目" prop="intentionProject">
                        <el-select
                            v-model="infoForm.intentionProject"
                            placeholder="请选择意向项目"
                            clearable
                            @focus="handleSelectFocus('intentionProject')"
                            filterable
                            :loading="dropdownLoading"
                        >
                            <el-option
                                v-for="item in dropdownData.intentionProject"
                                :key="item.value"
                                :label="item.label"
                                :value="item.value"
                            />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="客户意向等级" prop="customerIntentionLevel">
                        <el-select v-model="infoForm.customerIntentionLevel" placeholder="请选择客户意向等级" style="width: 100%" clearable>
                            <el-option label="A级 (已缴纳意向金)" value="A级 (已缴纳意向金)"/>
                            <el-option label="B级 (1个月内可签约)" value="B级 (1个月内可签约)"/>
                            <el-option label="C级 (3个月内需持续培育)" value="C级 (3个月内需持续培育)"/>
                            <el-option label="D级 (明确表示无意向)" value="D级 (明确表示无意向)"/>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="拓客渠道来源" prop="customerSource">
                        <el-select v-model="infoForm.customerSource" placeholder="请选择拓客渠道来源" style="width: 100%" clearable>
                            <el-option label="自主招商(陌拜call客、电话销售)" value="自主招商(陌拜call客、电话销售)"/>
                            <el-option label="中介" value="中介"/>
                            <el-option label="新媒体/网络平台" value="新媒体/网络平台"/>
                            <el-option label="以商引商" value="以商引商"/>
                            <el-option label="陌拜电Call" value="陌拜电Call"/>
                            <el-option label="展会论坛" value="展会论坛"/>
                            <el-option label="人才渠道" value="人才渠道"/>
                            <el-option label="政府推荐" value="政府推荐"/>
                            <el-option label="公司资源" value="公司资源"/>
                            <el-option label="商会/协会资源" value="商会/协会资源"/>
                            <el-option label="同行载体推荐" value="同行载体推荐"/>
                            <el-option label="园内企业扩租" value="园内企业扩租"/>
                            <el-option label="其他" value="其他"/>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="来源具体说明" prop="customerSourceDesc">
                        <el-input v-model="infoForm.customerSourceDesc" placeholder="请输入来源具体说明" clearable/>
                    </el-form-item>

                    <el-form-item label="招商目的" prop="investmentPurpose">
                        <el-select v-model="infoForm.investmentPurpose" placeholder="请选择招商目的" style="width: 100%" clearable>
                            <el-option label="人才申报" value="人才申报"/>
                            <el-option label="载体去化" value="载体去化"/>
                            <el-option label="税收" value="税收"/>
                            <el-option label="渠道" value="渠道"/>
                            <el-option label="产业资源" value="产业资源"/>
                            <el-option label="政府资源" value="政府资源"/>
                            <el-option label="其他" value="其他"/>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="所属行业" prop="industry">
                        <el-select v-model="infoForm.industry" placeholder="请选择所属行业" style="width: 100%" clearable>
                            <el-option label="医疗行业机构" value="医疗行业机构"/>
                            <el-option label="药品药物研发、生产及销售" value="药品药物研发、生产及销售"/>
                            <el-option label="医疗器械研发、生产及销售" value="医疗器械研发、生产及销售"/>
                            <el-option label="医疗器械销售(注册人制公司)" value="医疗器械销售(注册人制公司)"/>
                            <el-option label="医疗端即质行业机构-医生集团运营" value="医疗端即质行业机构-医生集团运营"/>
                            <el-option label="智慧养老(适老化改造/智能家居)" value="智慧养老(适老化改造/智能家居)"/>
                            <el-option label="健康产品电商与直播运营" value="健康产品电商与直播运营"/>
                            <el-option label="环境治理（技术解决方案及施工运维）" value="环境治理（技术解决方案及施工运维）"/>
                            <el-option label="环境检测" value="环境检测"/>
                            <el-option label="环境咨询（环境影响评估、场地环境调查）" value="环境咨询（环境影响评估、场地环境调查）"/>
                            <el-option label="低空经济" value="低空经济"/>
                            <el-option label="新能源" value="新能源"/>
                            <el-option label="新一代信息技术" value="新一代信息技术"/>
                            <el-option label="现代服务业与金融" value="现代服务业与金融"/>
                            <el-option label="房地产与建筑工程" value="房地产与建筑工程"/>
                            <el-option label="交通运输" value="交通运输"/>
                            <el-option label="商业销售" value="商业销售"/>
                            <el-option label="工业销售" value="工业销售"/>
                            <el-option label="新材料" value="新材料"/>
                            <el-option label="文化创意" value="文化创意"/>
                            <el-option label="现代农业科技" value="现代农业科技"/>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="企业所在地区" prop="enterpriseAddress">
                        <el-cascader
                            v-model="infoForm.enterpriseAddress"
                            :options="processedRegionData"
                            clearable
                            :props="{ expandTrigger: 'hover' }"
                            placeholder="请选择企业所在地区"        style="width: 100%"
                        />
                    </el-form-item>

                    <el-form-item label="客户资源能力" prop="resourceCapability">
                        <el-select v-model="infoForm.resourceCapability" placeholder="请选择客户资源能力" style="width: 100%" clearable>
                            <el-option label="无" value="无"/>
                            <el-option label="企业出海" value="企业出海"/>
                            <el-option label="资源引荐" value="资源引荐"/>
                            <el-option label="客户推介" value="客户推介"/>
                            <el-option label="政策支持指导" value="政策支持指导"/>
                            <el-option label="应用场景提供" value="应用场景提供"/>
                            <el-option label="产业规划" value="产业规划"/>
                            <el-option label="校友资源" value="校友资源"/>
                            <el-option label="同乡资源" value="同乡资源"/>
                            <el-option label="产业导师" value="产业导师"/>
                            <el-option label="上下游链接" value="上下游链接"/>
                            <el-option label="产学研合作" value="产学研合作"/>
                            <el-option label="校地企合作" value="校地企合作"/>
                            <el-option label="企业申报服务" value="企业申报服务"/>
                            <el-option label="法律服务" value="法律服务"/>
                            <el-option label="投融资服务" value="投融资服务"/>
                            <el-option label="健康服务" value="健康服务"/>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="客户入驻形态" prop="checkInType">
                        <el-select v-model="infoForm.checkInType" placeholder="请选择客户入驻形态" style="width: 100%" clearable>
                            <el-option label="实体-新注册" value="实体-新注册"/>
                            <el-option label="未定" value="未定"/>
                            <el-option label="实体-迁址" value="实体-迁址"/>
                            <el-option label="挂靠-新注册" value="挂靠-新注册"/>
                            <el-option label="挂靠-迁址" value="挂靠-迁址"/>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="企业资质" prop="enterpriseQualification">
                        <el-select v-model="infoForm.enterpriseQualification" placeholder="请选择企业资质" style="width: 100%" clearable>
                            <el-option label="高新技术企业" value="高新技术企业"/>
                            <el-option label="专精特新 “小巨人“" value="专精特新”小巨人“"/>
                            <el-option label="创新型中小企业" value="创新型中小企业"/>
                            <el-option label="科技型中小企业" value="科技型中小企业"/>
                            <el-option label="中小微企业" value="中小微企业"/>
                            <el-option label="独角兽" value="独角兽"/>
                            <el-option label="瞪羚企业" value="瞪羚企业"/>
                            <el-option label="其他" value="其他"/>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="企业人数" prop="employeeCount">
                        <el-select v-model="infoForm.employeeCount" placeholder="请选择企业人数" style="width: 100%" clearable>
                            <el-option label="< 10" value="< 10"/>
                            <el-option label="10-50" value="10-50"/>
                            <el-option label="50-200" value="50-200"/>
                            <el-option label="> 200" value="> 200"/>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="上年营收(万元)" prop="annualSales">
                        <el-input v-model="infoForm.annualSales" placeholder="请输入上年营收" clearable/>
                    </el-form-item>

                    <el-form-item label="上年税收(万元)" prop="annualTax">
                        <el-input v-model="infoForm.annualTax" placeholder="请输入上年税收" clearable/>
                    </el-form-item>

                    <el-form-item label="预计达成时间" prop="estimatedAchievementTime">
                        <el-date-picker
                            v-model="infoForm.estimatedAchievementTime"
                            type="date"
                            clearable
                            placeholder="请选择预计达成时间"
                            style="width: 100%"
                        />
                    </el-form-item>

                    <el-form-item label="主营业务" prop="mainBusiness">
                        <el-input
                            v-model="infoForm.mainBusiness"
                            placeholder="请输入主营业务"
                            type="textarea"
                            :rows="4"
                        />
                    </el-form-item>

                    <el-form-item label="主要关注点" prop="focusPoint">
                        <el-input
                            v-model="infoForm.focusPoint"
                            placeholder="请输入主要关注点"
                            type="textarea"
                            :rows="4"
                        />
                    </el-form-item>
                </template>

                <!-- 非企业客户显示的字段 (customerId以"qd"开头) -->
                <template v-else-if="currentCompany.customerId && currentCompany.customerId.startsWith('qd')">
                    <el-form-item label="渠道级别" prop="channelLevel">
                        <el-select v-model="infoForm.channelLevel" placeholder="请选择渠道级别" style="width: 100%">
                            <el-option label="公司级" value="公司级"/>
                            <el-option label="项目部门级" value="项目部门级"/>
                            <el-option label="个人级" value="个人级"/>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="归属部门" prop="attribution">
                        <el-select v-model="infoForm.attribution" placeholder="请选择归属部门" style="width: 100%">
                            <el-option label="联健元和" value="联健元和" />
                            <el-option label="达博" value="达博" />
                            <el-option label="科澜项目" value="科澜项目" />
                            <el-option label="国科项目" value="国科项目" />
                            <el-option label="黄埭项目" value="黄埭项目" />
                            <el-option label="金扶梯" value="金扶梯" />
                            <el-option label="北联新翼" value="北联新翼" />
                            <el-option label="深圳项目" value="深圳项目" />
                            <el-option label="西山项目" value="西山项目" />
                            <el-option label="秦淮项目" value="秦淮项目" />
                            <el-option label="双创中心" value="双创中心" />
                            <el-option label="创界项目" value="创界项目" />
                            <el-option label="江环项目" value="江环项目" />
                            <el-option label="江北项目" value="江北项目" />
                            <el-option label="拓展项目" value="拓展项目" />
                            <el-option label="试点项目" value="试点项目" />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="渠道分类" prop="category">
                        <el-select v-model="infoForm.category" placeholder="请选择渠道分类" style="width: 100%">
                            <el-option label="政府部门" value="政府机构"/>
                            <el-option label="商会协会" value="行业协会"/>
                            <el-option label="会所律所" value="行业协会"/>
                            <el-option label="中介服务" value="行业协会"/>
                            <el-option label="合作企业" value="行业协会"/>
                            <el-option label="财税公司" value="中介机构"/>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="是否签约" prop="isSigned">
                        <el-select v-model="infoForm.isSigned" placeholder="请选择是否签约" style="width: 100%">
                            <el-option label="已签约" value="已签约"/>
                            <el-option label="未签约" value="未签约"/>
                        </el-select>
                    </el-form-item>
                </template>
            </el-form>

            <template #footer>
        <span class="dialog-footer">
            <el-button @click="handleInfoDialogClose">取消</el-button>
            <el-button type="primary" @click="submitInfoForm">保存</el-button>
        </span>
            </template>
        </el-dialog>


        <!-- 新增客户弹窗 -->
        <el-dialog
            v-model="addDialogVisible"
            title="新增客户"
            width="600px"
            :before-close="handleAddDialogClose"
        >
            <el-form
                ref="addFormRef"
                :model="addForm"
                :rules="addRules"
                label-width="120px"
                class="info-form"
            >
                <el-form-item label="部门" prop="department">
                    <el-input v-model="addForm.department" placeholder="部门" disabled />
                </el-form-item>

                <el-form-item label="招商员" prop="businessDeveloper">
                    <el-input v-model="addForm.businessDeveloper" placeholder="招商员" disabled />
                </el-form-item>

                <el-form-item label="客户类型" prop="investmentTarget" required>
                    <el-select
                        v-model="addForm.investmentTarget"
                        placeholder="请选择客户类型"
                        style="width: 100%"
                        @change="handleInvestmentTargetChange"
                    >
                        <el-option label="企业客户" value="企业客户" />
                        <el-option label="招商渠道" value="招商渠道" />
                    </el-select>
                </el-form-item>

                <el-form-item label="客户名称" prop="companyName" required>
                    <el-input v-model="addForm.companyName" placeholder="请输入客户名称"/>
                </el-form-item>

                <el-form-item label="联系人" prop="contactPerson" required>
                    <el-input v-model="addForm.contactPerson" placeholder="请输入联系人"/>
                </el-form-item>

                <el-form-item label="联系方式" prop="contactMethod" required>
                    <el-select
                        v-model="addForm.contactMethod"
                        placeholder="请选择联系方式"
                        style="width: 100%"
                        @change="handleContactMethodChange"
                    >
                        <el-option label="手机" value="mobile"/>
                        <el-option label="微信" value="wechat"/>
                    </el-select>
                </el-form-item>

                <!-- 修改联系人手机号码输入框 -->
                <el-form-item
                    :label="addForm.contactMethod === 'mobile' ? '手机号码' : '微信号'"
                    :prop="addForm.contactMethod === 'mobile' ? 'contactPhone' : 'contactWx'"
                    required
                >
                    <el-input
                        v-if="addForm.contactMethod === 'mobile'"
                        v-model="addForm.contactPhone"
                        :placeholder="addForm.contactMethod === 'mobile' ? '请输入手机号码' : '请输入微信号'"
                    />
                    <el-input
                        v-else
                        v-model="addForm.contactWx"
                        :placeholder="addForm.contactMethod === 'mobile' ? '请输入手机号码' : '请输入微信号'"
                    />
                </el-form-item>

                <!-- 企业客户显示的字段 -->
                <template v-if="addForm.investmentTarget === '企业客户'">
                    <el-form-item label="客户意向等级" prop="customerIntentionLevel" required>
                        <el-select v-model="addForm.customerIntentionLevel" placeholder="请选择客户意向等级" style="width: 100%">
                            <el-option label="A级 (已缴纳意向金)" value="A级 (已缴纳意向金)"/>
                            <el-option label="B级 (1个月内可签约)" value="B级 (1个月内可签约)"/>
                            <el-option label="C级 (3个月内需持续培育)" value="C级 (3个月内需持续培育)"/>
                            <el-option label="D级 (明确表示无意向)" value="D级 (明确表示无意向)"/>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="渠道来源" prop="customerSource" required>
                        <el-select v-model="addForm.customerSource" placeholder="请选择拓客渠道来源" style="width: 100%">
                            <el-option label="自主招商(陌拜call客、电话销售)" value="自主招商(陌拜call客、电话销售)"/>
                            <el-option label="中介" value="中介"/>
                            <el-option label="新媒体/网络平台" value="新媒体/网络平台"/>
                            <el-option label="以商引商" value="以商引商"/>
                            <el-option label="陌拜电Call" value="陌拜电Call"/>
                            <el-option label="展会论坛" value="展会论坛"/>
                            <el-option label="人才渠道" value="人才渠道"/>
                            <el-option label="政府推荐" value="政府推荐"/>
                            <el-option label="公司资源" value="公司资源"/>
                            <el-option label="商会/协会资源" value="商会/协会资源"/>
                            <el-option label="同行载体推荐" value="同行载体推荐"/>
                            <el-option label="园内企业扩租" value="园内企业扩租"/>
                            <el-option label="其他" value="其他"/>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="渠道名称" prop="customerSourceDesc" required>
                        <el-input v-model="addForm.customerSourceDesc" placeholder="请输入渠道名称"/>
                    </el-form-item>
                </template>

                <!-- 非企业客户显示的字段 -->
                <template v-else-if="addForm.investmentTarget">
                    <el-form-item label="渠道级别" prop="channelLevel" required>
                        <el-select v-model="addForm.channelLevel" placeholder="请选择渠道级别" style="width: 100%">
                            <el-option label="公司级" value="公司级"/>
                            <el-option label="项目部门级" value="项目部门级"/>
                            <el-option label="个人级" value="个人级"/>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="归属部门" prop="attribution" required>
                        <el-select v-model="addForm.attribution" placeholder="请选择归属部门" style="width: 100%">
                            <el-option label="联健元和" value="联健元和" />
                            <el-option label="达博" value="达博" />
                            <el-option label="科澜项目" value="科澜项目" />
                            <el-option label="国科项目" value="国科项目" />
                            <el-option label="黄埭项目" value="黄埭项目" />
                            <el-option label="金扶梯" value="金扶梯" />
                            <el-option label="北联新翼" value="北联新翼" />
                            <el-option label="深圳项目" value="深圳项目" />
                            <el-option label="西山项目" value="西山项目" />
                            <el-option label="秦淮项目" value="秦淮项目" />
                            <el-option label="双创中心" value="双创中心" />
                            <el-option label="创界项目" value="创界项目" />
                            <el-option label="江环项目" value="江环项目" />
                            <el-option label="江北项目" value="江北项目" />
                            <el-option label="拓展项目" value="拓展项目" />
                            <el-option label="试点项目" value="试点项目" />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="渠道分类" prop="category" required>
                        <el-select v-model="addForm.category" placeholder="请选择渠道分类" style="width: 100%">
                            <el-option label="政府部门" value="政府机构"/>
                            <el-option label="商会协会" value="行业协会"/>
                            <el-option label="会所律所" value="行业协会"/>
                            <el-option label="中介服务" value="行业协会"/>
                            <el-option label="合作企业" value="行业协会"/>
                            <el-option label="财税公司" value="中介机构"/>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="是否签约" prop="isSigned" required>
                        <el-select v-model="addForm.isSigned" placeholder="请选择是否签约" style="width: 100%">
                            <el-option label="已签约" value="已签约"/>
                            <el-option label="未签约" value="未签约"/>
                        </el-select>
                    </el-form-item>
                </template>
            </el-form>

            <template #footer>
        <span class="dialog-footer">
            <el-button @click="handleAddDialogClose">取消</el-button>
            <el-button type="primary" @click="submitAddForm">提交</el-button>
        </span>
            </template>
        </el-dialog>


        <!-- 联系人维护抽屉 -->
        <el-drawer
            v-model="contactDrawerVisible"
            title="联系人信息"
            :before-close="handleCloseContactDrawer"
            size="60%"
            direction="rtl"
            :show-close="true"
            :destroy-on-close="true"
        >
            <div class="drawer-content">
                <div class="company-header">
                    <h3>{{ currentCompany.companyName }}</h3>
                </div>

                <div class="basic-info">
                    <div class="info-item">
                        <span class="label">报备部门：</span>
                        <span class="value">{{ currentCompany.department || '暂无' }}</span>
                    </div>
                    <div class="info-item">
                        <span class="label">招商员：</span>
                        <span class="value">{{ currentCompany.businessDeveloper || '暂无' }}</span>
                    </div>
                </div>

                <div class="contact-list">
                    <div v-if="contactList.length === 0" class="empty-tip">
                        暂无联系人
                    </div>

                    <div v-for="(contact, index) in contactList" :key="index" class="contact-item">
                        <div class="contact-header" @click="toggleContactDetail(index)">
                            <div class="info-item">
                                <span class="label">姓名：</span>
                                <span class="value">{{ contact.contactName }}</span>
                                <div class="action-buttons">
                                    <el-button type="primary" link @click="editContact(contact)">编辑</el-button>
                                    <el-button
                                        v-if="contactList.length > 1"
                                        type="danger"
                                        link
                                        @click.stop="deleteContact(contact.id, index)"
                                    >
                                        删除
                                    </el-button>
                                </div>
                            </div>
                            <div class="info-item">
                                <span class="label">手机：</span>
                                <span class="value">{{ contact.mobile }}</span>
                            </div>
                            <div class="expand-icon">
                                <el-icon :class="{ 'rotate': contact.expanded }">
                                    <ArrowDown />
                                </el-icon>
                            </div>
                        </div>

                        <div v-if="contact.expanded" class="contact-detail">
                            <div class="info-item">
                                <span class="label">籍贯：</span>
                                <span class="value">
                                    {{ contact.nativeProvince || '' }}
                                    {{ contact.nativeCity || '' }}
                                    {{ contact.nativeDistrict || '' }}
                                    <template v-if="!contact.nativeProvince && !contact.nativeCity && !contact.nativeDistrict">
                                        暂无
                                    </template>
                                </span>
                            </div>
                            <div class="info-item">
                                <span class="label">职务/头衔：</span>
                                <span class="value">{{ contact.position || '暂无' }}</span>
                            </div>
                            <div class="info-item">
                                <span class="label">毕业院校：</span>
                                <span class="value">{{ contact.graduateSchool || '暂无' }}</span>
                            </div>
                            <!--                            <div class="info-item">-->
                            <!--                                <span class="label">首要联系人：</span>-->
                            <!--                                <span class="value">{{ contact.isPrimaryContact ? '是' : '否' }}</span>-->
                            <!--                            </div>-->
                            <div class="info-item">
                                <span class="label">学历：</span>
                                <span class="value">{{ contact.education || '暂无' }}</span>
                            </div>
                            <div class="info-item">
                                <span class="label">个人爱好：</span>
                                <span class="value">{{ contact.personalHobby || '暂无' }}</span>
                            </div>
                            <!--                            <div class="info-item">-->
                            <!--                                <span class="label">联系人邮箱：</span>-->
                            <!--                                <span class="value">{{ contact.email || '暂无' }}</span>-->
                            <!--                            </div>-->
                            <!--                            <div class="info-item">-->
                            <!--                                <span class="label">联系人QQ：</span>-->
                            <!--                                <span class="value">{{ contact.qq || '暂无' }}</span>-->
                            <!--                            </div>-->
                            <div class="info-item">
                                <span class="label">联系人微信：</span>
                                <span class="value">{{ contact.wechat || '暂无' }}</span>
                            </div>
                            <div class="info-item">
                                <span class="label">亲密程度：</span>
                                <span class="value">{{ contact.intimacyLevel || '暂无' }}</span>
                            </div>
                            <div class="info-item">
                                <span class="label">备注：</span>
                                <span class="value">{{ contact.remark || '暂无' }}</span>
                            </div>

                        </div>
                    </div>

                </div>

                <div class="add-contact-btn">
                    <el-button type="primary" icon="Plus" @click="openAddContactForm">
                        新增联系人（可添加多个）
                    </el-button>
                </div>
            </div>
        </el-drawer>
        <CompanyDetailDrawer
            ref="detailDrawerRef"
            :detail="followDetail"
            :relatedFollowList="relatedFollowList"
        />
        <!-- 编辑联系人弹窗 -->
        <el-dialog
            v-model="editContactDialogVisible"
            title="编辑联系人"
            width="600px"
            :before-close="handleEditContactClose"
        >
            <el-form
                ref="editContactFormRef"
                :model="editContactForm"
                :rules="editContactRules"
                label-width="120px"
                class="info-form"
            >
                <el-form-item label="公司名称" prop="companyName">
                    <el-input v-model="editContactForm.companyName" disabled />
                </el-form-item>

                <el-form-item label="联系人姓名" prop="contactName">
                    <el-input v-model="editContactForm.contactName" placeholder="请输入联系人姓名"/>
                </el-form-item>

                <el-form-item label="职务/头衔" prop="position">
                    <el-input v-model="editContactForm.position" placeholder="请输入职务/头衔"/>
                </el-form-item>

                <el-form-item label="联系人手机" prop="mobile">
                    <el-input v-model="editContactForm.mobile" placeholder="请输入联系人手机"/>
                </el-form-item>

                <el-form-item label="微信号" prop="wechat">
                    <el-input v-model="editContactForm.wechat" placeholder="请输入微信号"/>
                </el-form-item>

                <el-form-item label="联系人籍贯" prop="nativeAddress">
                    <el-cascader
                        v-model="editContactForm.nativeAddress"
                        :options="regionData"
                        :props="{ expandTrigger: 'hover' }"
                        placeholder="请选择籍贯"    style="width: 100%"
                    />
                </el-form-item>

                <el-form-item label="公司角色" prop="relationship">
                    <el-select v-model="editContactForm.relationship" placeholder="请选择公司角色" style="width: 100%">
                        <el-option label="法人" value="法人"/>
                        <el-option label="主办会计" value="主办会计"/>
                        <el-option label="主要负责人" value="主要负责人"/>
                        <el-option label="日常联系人" value="日常联系人"/>
                        <el-option label="租住使用人" value="租住使用人"/>
                    </el-select>
                </el-form-item>

                <el-form-item label="联系人性别" prop="gender">
                    <el-select v-model="editContactForm.gender" placeholder="请选择性别" style="width: 100%">
                        <el-option label="男" value="男"/>
                        <el-option label="女" value="女"/>
                    </el-select>
                </el-form-item>

                <el-form-item label="联系人学历" prop="education">
                    <el-select v-model="editContactForm.education" placeholder="请选择学历" style="width: 100%">
                        <el-option label="高中及以下" value="高中及以下"/>
                        <el-option label="大专" value="大专"/>
                        <el-option label="本科" value="本科"/>
                        <el-option label="硕士" value="硕士"/>
                        <el-option label="博士" value="博士"/>
                    </el-select>
                </el-form-item>

                <el-form-item label="毕业院校及专业" prop="graduateSchool">
                    <el-input v-model="editContactForm.graduateSchool" placeholder="请输入毕业院校及专业"/>
                </el-form-item>

                <el-form-item label="联系人年龄" prop="contactAge">
                    <el-input v-model="editContactForm.contactAge" placeholder="具体年龄或者年龄范围 (30-35,35-40, ...)"/>
                </el-form-item>

                <el-form-item label="联系人生日" prop="birthday">
                    <el-date-picker
                        v-model="editContactForm.birthday"
                        type="date"
                        placeholder="选择联系人生日"                style="width: 100%"
                    />
                </el-form-item>

                <el-form-item label="亲密程度" prop="intimacyLevel">
                    <el-select v-model="editContactForm.intimacyLevel" placeholder="请选择亲密程度" style="width: 100%">
                        <el-option label="初相识" value="初相识"/>
                        <el-option label="一般关系" value="一般关系"/>
                        <el-option label="朋友关系" value="朋友关系"/>
                        <el-option label="好友关系" value="好友关系"/>
                    </el-select>
                </el-form-item>

                <el-form-item label="个人爱好" prop="personalHobby">
                    <el-input v-model="editContactForm.personalHobby" placeholder="请输入个人爱好"/>
                </el-form-item>

                <el-form-item label="其他备注" prop="remark">
                    <el-input
                        v-model="editContactForm.remark"
                        placeholder="请输入其他备注"
                        type="textarea"
                        :rows="4"
                    />
                </el-form-item>
            </el-form>

            <template #footer>
        <span class="dialog-footer">
            <el-button @click="handleEditContactClose">取消</el-button>
            <el-button type="primary" @click="submitEditContactForm">保存</el-button>
        </span>
            </template>
        </el-dialog>
        <!-- 新增联系人弹窗 -->
        <el-dialog
            v-model="addContactDialogVisible"
            title="新增联系人"
            width="600px"
            :before-close="handleAddContactClose"
        >
            <el-form
                ref="addContactFormRef"
                :model="addContactForm"
                :rules="addContactRules"
                label-width="120px"
                class="info-form"
            >
                <el-form-item label="公司名称" prop="companyName">
                    <el-input v-model="addContactForm.companyName" disabled />
                </el-form-item>

                <el-form-item label="联系人姓名" prop="contactName">
                    <el-input v-model="addContactForm.contactName" placeholder="请输入联系人姓名"/>
                </el-form-item>

                <el-form-item label="职务/头衔" prop="position">
                    <el-input v-model="addContactForm.position" placeholder="请输入职务/头衔"/>
                </el-form-item>

                <el-form-item label="联系人手机" prop="mobile">
                    <el-input v-model="addContactForm.mobile" placeholder="请输入联系人手机"/>
                </el-form-item>

                <el-form-item label="微信号" prop="wechat">
                    <el-input v-model="addContactForm.wechat" placeholder="请输入微信号"/>
                </el-form-item>

                <el-form-item label="联系人籍贯" prop="nativeAddress">
                    <el-cascader
                        v-model="editContactForm.nativeAddress"
                        :options="regionData"
                        :props="{ expandTrigger: 'hover' }"
                        placeholder="请选择籍贯"    style="width: 100%"
                    />
                </el-form-item>

                <el-form-item label="公司角色" prop="relationship">
                    <el-select v-model="addContactForm.relationship" placeholder="请选择公司角色" style="width: 100%">
                        <el-option label="法人" value="法人"/>
                        <el-option label="主办会计" value="主办会计"/>
                        <el-option label="主要负责人" value="主要负责人"/>
                        <el-option label="日常联系人" value="日常联系人"/>
                        <el-option label="租住使用人" value="租住使用人"/>
                    </el-select>
                </el-form-item>

                <el-form-item label="联系人性别" prop="gender">
                    <el-select v-model="addContactForm.gender" placeholder="请选择性别" style="width: 100%">
                        <el-option label="男" value="男"/>
                        <el-option label="女" value="女"/>
                    </el-select>
                </el-form-item>

                <el-form-item label="联系人学历" prop="education">
                    <el-select v-model="addContactForm.education" placeholder="请选择学历" style="width: 100%">
                        <el-option label="高中及以下" value="高中及以下"/>
                        <el-option label="大专" value="大专"/>
                        <el-option label="本科" value="本科"/>
                        <el-option label="硕士" value="硕士"/>
                        <el-option label="博士" value="博士"/>
                    </el-select>
                </el-form-item>

                <el-form-item label="毕业院校及专业" prop="graduateSchool">
                    <el-input v-model="addContactForm.graduateSchool" placeholder="请输入毕业院校及专业"/>
                </el-form-item>

                <el-form-item label="联系人年龄" prop="contactAge">
                    <el-input v-model="addContactForm.contactAge" placeholder="具体年龄或者年龄范围 (30-35,35-40, ...)"/>
                </el-form-item>

                <el-form-item label="联系人生日" prop="birthday">
                    <el-date-picker
                        v-model="addContactForm.birthday"
                        type="date"
                        placeholder="选择联系人生日"
                        style="width: 100%"
                    />
                </el-form-item>

                <el-form-item label="亲密程度" prop="intimacyLevel">
                    <el-select v-model="addContactForm.intimacyLevel" placeholder="请选择亲密程度" style="width: 100%">
                        <el-option label="初相识" value="初相识"/>
                        <el-option label="一般关系" value="一般关系"/>
                        <el-option label="朋友关系" value="朋友关系"/>
                        <el-option label="好友关系" value="好友关系"/>
                    </el-select>
                </el-form-item>

                <el-form-item label="个人爱好" prop="personalHobby">
                    <el-input v-model="addContactForm.personalHobby" placeholder="请输入个人爱好"/>
                </el-form-item>

                <el-form-item label="其他备注" prop="remark">
                    <el-input
                        v-model="addContactForm.remark"
                        placeholder="请输入其他备注"
                        type="textarea"
                        :rows="4"
                    />
                </el-form-item>
            </el-form>

            <template #footer>
        <span class="dialog-footer">
            <el-button @click="handleAddContactClose">取消</el-button>
            <el-button type="primary" @click="submitAddContactForm">保存</el-button>
        </span>
            </template>
        </el-dialog>




        <!-- 新增跟进记录 -->
        <el-dialog
            v-model="dialogAddFollowUpVisible"
            title="新增跟进记录"
            width="600px"
            :before-close="handleCloseFollowUp"
        >
            <el-form
                ref="formRefFollowUp"
                :model="formDataAddFollow"
                :rules="addFollowRecodeRules"
                label-width="120px"
                size="small"
            >
                <!-- 目标客户 -->
                <el-form-item label="目标客户">
                    <el-input v-model="formDataAddFollow.companyName" style="width: 100%;" disabled />
                </el-form-item>

                <!-- 陪访人员 -->
                <el-form-item label="陪访人员">
                    <el-select
                        v-model="formDataAddFollow.accompanyStaff"
                        placeholder="请选择"
                        style="width: 100%"
                        multiple
                        filterable
                        remote
                        :remote-method="filterAccompanyingVisitors"
                        :loading="accompanyingVisitorLoading"
                        reserve-keyword
                    >
                        <el-option
                            v-for="(visitor, index) in filteredAccompanyingVisitorList"
                            :key="index"
                            :label="visitor"
                            :value="visitor"
                        />
                    </el-select>
                </el-form-item>

                <!-- 招商对象企业 -->
                <!-- <el-form-item label="招商对象企业" prop="targetEnterprise">
                <el-select v-model="formDataAddFollow.investmentTarget" placeholder="请选择" style="width: 40%;">
                    <el-option label="企业" value="企业" />
                    <el-option label="项目" value="项目" />
                    <el-option label="机构" value="机构" />
                </el-select>
                </el-form-item> -->


                <!-- 联系人 -->
                <el-form-item label="联系人" prop="contactPerson">
                    <el-select v-model="formDataAddFollow.contactPerson" placeholder="请选择" style="width: 85%;">
                        <el-option
                            v-for="(dept, index) in AddFollowContactList"
                            :key="index"
                            :label="dept"
                            :value="dept"
                        />
                    </el-select>
                    <el-button type="primary" icon="Plus" size="small" style="margin-left: 8px;" @click="openAddContactForm"></el-button>
                </el-form-item>



                <!-- 跟进方式 -->
                <el-form-item label="跟进方式" prop="followUpType">
                    <el-select v-model="formDataAddFollow.followUpType" placeholder="请选择" style="width: 100%;">
                        <el-option label="上门拜访" value="上门拜访" />
                        <el-option label="来访接待" value="来访接待" />
                        <el-option label="园内走访" value="园内走访" />
                        <el-option label="电话拜访" value="电话拜访" />
                        <el-option label="QQ微信联系" value="QQ微信联系" />
                    </el-select>
                </el-form-item>

                <!-- 客户意向等级 -->
                <el-form-item label="客户意向等级" prop="customerIntentionLevel">
                    <el-select v-model="formDataAddFollow.customerIntentionLevel" placeholder="请选择" style="width: 100%;">
                        <el-option label="A级 (已缴纳意向金)" value="A级 (已缴纳意向金)"/>
                        <el-option label="B级 (1个月内可签约)" value="B级 (1个月内可签约)"/>
                        <el-option label="C级 (3个月内需持续培育)" value="C级 (3个月内需持续培育)"/>
                        <el-option label="D级 (明确表示无意向)" value="D级 (明确表示无意向)"/>
                    </el-select>
                </el-form-item>

                <!-- 招商对象 :企业 政府部门 中介 第三方公司 同行载体-->
<!--                <el-form-item label="客户类型" prop="investmentTarget">-->
<!--                    <el-select v-model="formDataAddFollow.investmentTarget" placeholder="请选择" style="width: 100%;">-->
<!--                        <el-option label="企业客户" value="企业客户" />-->
<!--                        <el-option label="招商渠道" value="招商渠道" />-->
<!--                    </el-select>-->
<!--                </el-form-item>-->

                <!-- 招商阶段：线上沟通询问，初次线下接触，二次及以上拜访，首次带看，二次及以上带看，商谈合同要素，定金缴纳 -->
                <el-form-item label="招商阶段" prop="customerProgress">
                    <el-select v-model="formDataAddFollow.customerProgress" placeholder="请选择" style="width: 100%;">
                        <el-option label="线上沟通询问" value="线上沟通询问" />
                        <el-option label="初次线下接触" value="初次线下接触" />
                        <el-option label="二次及以上拜访" value="二次及以上拜访" />
                        <el-option label="首次带看" value="首次带看" />
                        <el-option label="二次及以上带看" value="二次及以上带看" />
                        <el-option label="商谈合同要素" value="商谈合同要素" />
                        <el-option label="定金缴纳" value="定金缴纳" />
                    </el-select>
                </el-form-item>

                <!-- 跟进时间 -->
                <el-form-item label="跟进时间" prop="followUpTime">
                    <!-- 日期选择器，默认当天 -->
                    <el-date-picker
                        v-model="formDataAddFollow.followUpDate"
                        type="date"
                        placeholder="选择日期"
                        :disabled-date="followDateOptions1.disabledDate1"
                        style="width: 48%"
                        @change="handleDateChange"
                    />
                    <!-- 时间选择器，可选择时分秒 -->
                    <el-time-picker
                        v-model="formDataAddFollow.followUpTime"
                        placeholder="选择时间"
                        format="HH:mm:ss"
                        value-format="HH:mm:ss"
                        style="width: 48%; margin-left: 4%"
                    />
                </el-form-item>
                <!-- 跟进记录 -->
                <el-form-item label="跟进记录" prop="followUpContent">
                    <el-input
                        v-model="formDataAddFollow.followUpContent"
                        type="textarea"
                        :rows="4"
                        placeholder="请填写跟进过程及结果，不少于10个字"
                        style="width: 100%;"
                    />
                </el-form-item>

                <!-- 修改下次跟进时间的表单项 -->
                <el-form-item label="下次跟进时间">
                    <el-date-picker
                        v-model="formDataAddFollow.replyTime"
                        type="date"
                        placeholder="请选择下次跟进时间"
                        :disabled-date="followDateOptions.disabledDate"
                        style="width: 48%"
                    />
                </el-form-item>
                <!-- 地图选择弹窗 -->
                <!-- <el-dialog
                v-model="mapDialogVisible"
                title="选择地理位置"
                width="800px"
                :before-close="handleMapDialogClose"
                >
                <div class="map-container">
                    <div id="mapContainer" style="width: 100%; height: 500px;"></div>
                    <div class="map-search">
                    <el-input
                        v-model="mapSearchKeyword"
                        placeholder="搜索地点"
                        style="width: 300px; margin-right: 10px;"
                        @keyup.enter="searchMapLocation"
                    />
                    <el-button type="primary" @click="searchMapLocation">搜索</el-button>
                    </div>
                    <div class="selected-address" v-if="selectedMapAddress">
                    <p>已选择地址：{{ selectedMapAddress }}</p>
                    </div>
                </div>
                <template #footer>
                    <span class="dialog-footer">
                    <el-button @click="handleMapDialogClose">取消</el-button>
                    <el-button type="primary" @click="confirmMapLocation">确定</el-button>
                    </span>
                </template>
                </el-dialog> -->
                <!-- 选择新增图片控件 -->
                <el-form-item label="请上传打卡图片" prop="attachmentUrl">
                    <div style="display: flex; align-items: center;">
                        <el-upload
                            :action="uploadUrl"
                            :before-upload="handleBeforeUpload"
                            :on-success="handleUploadSuccess"
                            :on-error="handleUploadError"
                            :http-request="handleUploadRequest"
                            name="file"
                            :show-file-list="false"
                            :headers="headers"
                            v-if="type == 'url'"
                        >
                            <!-- 根据是否有图片显示不同按钮 -->
                            <el-button
                                v-if="!formDataAddFollow.attachmentUrl"
                                size="large"
                                icon="Plus"
                                style="font-size: 35px;"
                            ></el-button>
                        </el-upload>

                        <!-- 图片回显显示和删除按钮 -->
                        <div v-if="formDataAddFollow.attachmentUrl" style="position: relative; margin-left: 10px;">
                            <img
                                :src="formDataAddFollow.attachmentUrl"
                                alt="上传的图片"
                                style="max-width: 200px; max-height: 200px; border: 1px solid #ddd; border-radius: 4px;"
                            />
                            <el-button
                                size="small"
                                type="danger"
                                icon="Delete"
                                @click.stop="handleDeleteImage"
                                style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); background-color: rgba(0, 0, 0, 0.3); border: none; padding: 5px;"
                            ></el-button>
                        </div>
                    </div>
                </el-form-item>
            </el-form>
            <template #footer>
            <span class="dialog-footer">
            <el-button @click="handleCloseFollowUp">关闭</el-button>
            <el-button type="primary" @click="handleSubmitFollowUp">保存</el-button>
            </span>
            </template>
        </el-dialog>
        <!--新申请弹窗-->
        <el-dialog
            title="提报迁址办证"
            v-model="reportDialogVisible"
            width="500px"
            :before-close="handleCloseReportDialog"
        >
            <el-form
                :model="reportForm"
                :rules="reportRules"
                ref="reportFormRef"
                label-width="100px"
            >
                <!-- 目标客户 -->
                <el-form-item label="目标客户" prop="companyName">
                    <el-input v-model="reportForm.companyName" placeholder="可更改为待报名名称(限1个),同步更新意向客户名称" />
                </el-form-item>

                <!-- 入住类型 -->
                <el-form-item label="入住类型" prop="entryMode">
                    <el-select v-model="reportForm.entryMode" placeholder="请选择">
                        <el-option label="实体" value="实体" />
                        <el-option label="挂靠" value="挂靠" />
                    </el-select>
                </el-form-item>

                <!-- 入驻项目 -->
                <el-form-item label="入驻项目" prop="zt">
                    <el-select v-model="reportForm.zt" placeholder="请选择">
                        <el-option label="联健元和" value="联健元和" />
                        <el-option label="达博" value="达博" />
                        <el-option label="科澜项目" value="科澜项目" />
                        <el-option label="国科项目" value="国科项目" />
                        <el-option label="黄埭项目" value="黄埭项目" />
                        <el-option label="金扶梯" value="金扶梯" />
                        <el-option label="北联新翼" value="北联新翼" />
                        <el-option label="深圳项目" value="深圳项目" />
                        <el-option label="西山项目" value="西山项目" />
                        <el-option label="秦淮项目" value="秦淮项目" />
                        <el-option label="双创中心" value="双创中心" />
                        <el-option label="创界项目" value="创界项目" />
                        <el-option label="江环项目" value="江环项目" />
                        <el-option label="江北项目" value="江北项目" />
                        <el-option label="拓展项目" value="拓展项目" />
                        <el-option label="试点项目" value="试点项目" />
                    </el-select>
                </el-form-item>

                <!-- 核办主体 -->
                <el-form-item label="核办主体" prop="authorizedEntity">
                    <el-select v-model="reportForm.authorizedEntity" placeholder="请选择">
                        <el-option label="我方代办" value="我方代办" />
                        <el-option label="客户自办" value="客户自办" />
                    </el-select>
                </el-form-item>

                <!-- 新注册地址 -->
                <el-form-item label="新注册地址" prop="roomNum">
                    <el-input v-model="reportForm.roomNum" placeholder="请具体到房间号或工位" />
                </el-form-item>

                <!-- 面积 -->
                <el-form-item label="面积" prop="area">
                    <el-input-number
                        v-model.number="reportForm.area"
                        :min="0"
                        placeholder="数据用于统计，请认真填写"
                        style="width: 100%"
                    />
                </el-form-item>
            </el-form>

            <template #footer>
                <el-button @click="reportDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitReportForm">提交</el-button>
            </template>
        </el-dialog>

        <!-- 迁址办证弹窗 -->
        <el-dialog
            title="提报迁址办证"
            v-model="relocationDialogVisible"
            width="500px"
            :before-close="handleCloseRelocationDialog"
        >
            <el-form
                :model="relocationForm"
                :rules="relocationRules"
                ref="relocationFormRef"
                label-width="100px"
            >
                <!-- 目标客户 -->
                <el-form-item label="目标客户" prop="companyName">
                    <el-input v-model="relocationForm.companyName" placeholder="可更改为待报名名称(限1个),同步更新意向客户名称" />
                </el-form-item>

                <!-- 入住类型 -->
                <el-form-item label="入住类型" prop="entryMode">
                    <el-select v-model="relocationForm.entryMode" placeholder="请选择">
                        <el-option label="实体" value="实体" />
                        <el-option label="挂靠" value="挂靠" />
                    </el-select>
                </el-form-item>

                <!-- 入驻项目 -->
                <el-form-item label="入驻项目" prop="zt">
                    <el-select v-model="relocationForm.zt" placeholder="请选择">
                        <el-option label="联健元和" value="联健元和" />
                        <el-option label="达博" value="达博" />
                        <el-option label="科澜项目" value="科澜项目" />
                        <el-option label="国科项目" value="国科项目" />
                        <el-option label="黄埭项目" value="黄埭项目" />
                        <el-option label="金扶梯" value="金扶梯" />
                        <el-option label="北联新翼" value="北联新翼" />
                        <el-option label="深圳项目" value="深圳项目" />
                        <el-option label="西山项目" value="西山项目" />
                        <el-option label="秦淮项目" value="秦淮项目" />
                        <el-option label="双创中心" value="双创中心" />
                        <el-option label="创界项目" value="创界项目" />
                        <el-option label="江环项目" value="江环项目" />
                        <el-option label="江北项目" value="江北项目" />
                        <el-option label="拓展项目" value="拓展项目" />
                        <el-option label="试点项目" value="试点项目" />
                    </el-select>
                </el-form-item>

                <!-- 核办主体 -->
                <el-form-item label="核办主体" prop="authorizedEntity">
                    <el-select v-model="relocationForm.authorizedEntity" placeholder="请选择">
                        <el-option label="我方代办" value="我方代办" />
                        <el-option label="客户自办" value="客户自办" />
                    </el-select>
                </el-form-item>

                <!-- 新注册地址 -->
                <el-form-item label="新注册地址" prop="roomNum">
                    <el-input v-model="relocationForm.roomNum" placeholder="请具体到房间号或工位" />
                </el-form-item>

                <!-- 面积 -->
                <el-form-item label="面积" prop="area">
                    <el-input-number
                        v-model.number="relocationForm.area"
                        :min="0"
                        placeholder="数据用于统计，请认真填写"                  style="width: 100%"
                    />
                </el-form-item>
            </el-form>

            <template #footer>
                <el-button @click="relocationDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="submitRelocationForm">提交</el-button>
            </template>
        </el-dialog>
        <!-- 放弃原因弹窗 -->
        <el-dialog
            v-model="abandonDialogVisible"
            title="退回公海池"
            width="500px"
            :before-close="handleCloseAbandonDialog"
        >
            <el-form
                ref="abandonFormRef"
                :model="abandonForm"
                :rules="abandonRules"
                label-width="100px"
            >
                <el-form-item label="退回原因" prop="abandonReason">
                    <el-input
                        v-model="abandonForm.abandonReason"
                        type="textarea"
                        :rows="4"
                        placeholder="请输入退回原因"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="handleCloseAbandonDialog">取消</el-button>
                <el-button type="primary" @click="submitAbandonForm">确定</el-button>
            </template>
        </el-dialog>

        <!-- 重新分配跟进人员弹窗 -->
        <el-dialog
            v-model="reassignDialogVisible"
            title="重新分配招商员"
            width="600px"
            :before-close="handleCloseReassignDialog"
        >
            <el-form
                ref="reassignFormRef"
                :model="reassignForm"
                :rules="reassignRules"
                label-width="120px"
            >
                <el-form-item label="目标客户">
                    <el-input v-model="reassignForm.companyName" disabled />
                </el-form-item>
                <el-form-item label="原招商员">
                    <el-input v-model="reassignForm.originalBusinessDeveloper" disabled />
                </el-form-item>
                <el-form-item label="原招商时间">
                    <el-input v-model="reassignForm.originalTimeRange" disabled />
                </el-form-item>
                <el-form-item label="新开始时间" prop="newStartTime" required>
                    <el-date-picker
                        v-model="reassignForm.newStartTime"
                        type="date"
                        placeholder="请选择新开始时间"
                        style="width: 100%"
                        :disabled-date="reassignDateOptions.disabledDate"
                        format="YYYY-MM-DD"
                        value-format="YYYY-MM-DD"
                    />
                </el-form-item>
                <el-form-item label="所在部门" prop="department">
                    <el-select
                        v-model="reassignForm.department"
                        placeholder="请选择所在部门"
                        style="width: 100%"
                        filterable
                        :loading="reassignDepartmentLoading"
                        @change="handleReassignDepartmentChange"
                    >
                        <el-option
                            v-for="item in reassignDepartmentList"
                            :key="item"
                            :label="item"
                            :value="item"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="新跟进招商员" prop="newBusinessDeveloper" required>
                    <el-select
                        v-model="reassignForm.newBusinessDeveloper"
                        placeholder="请选择新跟进招商员"
                        style="width: 100%"
                        filterable
                        :loading="reassignBusinessDeveloperLoading"
                        :disabled="!reassignForm.department"
                    >
                        <el-option
                            v-for="item in reassignBusinessDeveloperList"
                            :key="item"
                            :label="item"
                            :value="item"
                        />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="handleCloseReassignDialog">关闭</el-button>
                <el-button type="primary" @click="submitReassignForm">保存</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRouter } from "vue-router";
import {
    getCustomerListPage,
    selectCustomerListByCustomerId,
    updateCustomerInfo,
    addCustomerInfo, getCustomerContact,contacetInsert,
    updateScoreA,
    updateContacetInfo,
    getCustomerRequirementBycustomerId,
    addCustomerRequirement,
    updateCustomerRequirement,
    delCustomerContact,
    insertCompanyTotal,
    getBusinessDevelopers,
    updateBusinessDeveloperByCustomerId,
    getDepartmentList,
} from "@/api/AttractInvestment/customer/index.js";

import {addFollowRecord,
    getByCustomerCode,
    getById,
    getContactListByCustomerCode,
    getAccompanyingVisitorList,
    getAccompanyingVisitorListAll} from "@/api/AttractInvestment/follow/index.js";

import CompanyDetailDrawer from '@/views/AttractInvestment/follow/CompanyDetailDrawer.vue';
import { getBaseCodeInfoList } from "@/api/AttractInvestment/baseCode/index.js";

import useUserStore from '@/store/modules/user'
import { regionData } from 'element-china-area-data';

// 处理地区数据：将江苏省放在最前面，并确保包含台湾
const processedRegionData = (() => {
    if (!regionData || !Array.isArray(regionData)) {
        return regionData;
    }
    
    // 深拷贝数据
    const data = JSON.parse(JSON.stringify(regionData));
    
    // 查找江苏省和台湾省的索引
    let jiangsuIndex = -1;
    let taiwanIndex = -1;
    let hasTaiwan = false;
    
    data.forEach((item, index) => {
        // 查找江苏省（可能是"江苏省"或"江苏"）
        if (item.label === '江苏省' || item.label === '江苏') {
            jiangsuIndex = index;
        }
        // 查找台湾省（通过标签或编码710000）
        if (item.value === '710000' || 
            item.label === '台湾省' || 
            item.label === '台湾' || 
            item.label === '台湾地区' ||
            item.label?.includes('台湾')) {
            taiwanIndex = index;
            hasTaiwan = true;
        }
    });
    
    // 如果找到江苏省，将其移到最前面
    if (jiangsuIndex > 0) {
        const jiangsuItem = data.splice(jiangsuIndex, 1)[0];
        data.unshift(jiangsuItem);
    }
    
    // 如果没找到台湾省，添加台湾省数据
    if (!hasTaiwan) {
        // 添加台湾省数据（使用常见的台湾省编码 710000）
        data.push({
            value: '710000',
            label: '台湾省',
            children: [
                {
                    value: '710100',
                    label: '台北市',
                    children: []
                },
                {
                    value: '710200',
                    label: '新北市',
                    children: []
                },
                {
                    value: '710300',
                    label: '桃园市',
                    children: []
                },
                {
                    value: '710400',
                    label: '台中市',
                    children: []
                },
                {
                    value: '710500',
                    label: '台南市',
                    children: []
                },
                {
                    value: '710600',
                    label: '高雄市',
                    children: []
                }
            ]
        });
    }
    
    return data;
})();

// 图片上传↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
// 在 script setup 部分添加必要的导入
import { getCurrentInstance } from 'vue'
// 获取当前实例以访问 proxy
const { proxy } = getCurrentInstance()
const uploadUrl = ref(import.meta.env.VITE_APP_BASE_ZS_API + "/AttractInvestment/follow/submit"); // 上传的图片服务器地址
// 添加 type 变量定义
const type = ref('url');
// 添加 headers 变量定义（如果需要认证）
const headers = ref({
    // Authorization: 'Bearer your-token' // 根据实际需要添加
});
// 声明 props（如果需要 fileSize 属性）
const props = defineProps({
    fileSize: {
        type: Number,
        default: 20 // 默认文件大小限制为 2MB
    }
})

// 当意向项目选择发生变化时，重新查询对应的招商员
const businessDevelopers = ref([]);
// 根据意向项目获取招商员列表
const fetchBusinessDevelopers = async () => {
  // 如果意向项目为空，清空招商员列表
  if (!queryParams.intentionProject || 
      (Array.isArray(queryParams.intentionProject) && queryParams.intentionProject.length === 0)) {
    businessDevelopers.value = [];
    return;
  }
  
  dropdownLoading.value = true;
  try {
    const params = {
      intentionProject: Array.isArray(queryParams.intentionProject) 
        ? queryParams.intentionProject.join(',') 
        : queryParams.intentionProject,
    };
    const res = await getBusinessDevelopers(params);
    if (res && res.code === 200) {
      // 确保正确处理返回的数据
      businessDevelopers.value = res.data.map(item => ({
        label: item,
        value: item
      }));
    } else {
      businessDevelopers.value = [];
    }
  } catch (error) {
    console.error("获取招商员列表失败:", error);
    businessDevelopers.value = [];
  } finally {
    dropdownLoading.value = false;
  }
};

// 修改 handleBeforeUpload 函数
function handleBeforeUpload(file) {
    const type = ["image/jpeg", "image/jpg", "image/png", "image/svg"];
    const isJPG = type.includes(file.type);
    // 检验文件格式
    if (!isJPG) {
        proxy.$modal.msgWarning(`图片格式错误!`);
        return false;
    }
    // 校检文件大小（固定为 2MB 限制）
    const maxSize = 20;
    const isLt = file.size / 1024 / 1024 < maxSize;
    if (!isLt) {
        proxy.$modal.msgWarning(`上传文件大小不能超过 ${maxSize} MB!`);
        return false;
    }
    return true;
}

// 修改 handleUploadSuccess 函数
function handleUploadSuccess(res, file) {
    // 如果上传成功
    if (res.code == 200) {
        ElMessage.success("图片上传成功");
        if (res.msg) {
            formDataAddFollow.attachmentUrl = res.msg; // 假设返回的URL在res.data中
        }
        // 如果需要在其他地方使用上传的图片，可以在这里处理
    } else {
        proxy.$modal.msgError("图片上传失败");
    }
}

// 添加一个新的上传处理函数，使用 fetch 方式
async function handleUploadRequest(option) {
    const { file, onSuccess, onError } = option;

    const formData = new FormData();
    formData.append('file', file);

    try {
        const response = await fetch(import.meta.env.VITE_APP_BASE_ZS_API + "/AttractInvestment/follow/submit", {
            method: 'POST',
            body: formData
        });

        const result = await response.json();

        if (response.ok && result) {
            onSuccess(result, file);
        } else {
            onError(new Error(result.message || '上传失败'));
        }
    } catch (error) {
        onError(error);
    }
}
// 在 script setup 部分添加删除图片函数
function handleDeleteImage() {
    ElMessageBox.confirm('确定要删除这张图片吗？', '确认删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        // 清除图片URL
        const imageUrl=formDataAddFollow.attachmentUrl;
        formDataAddFollow.attachmentUrl = "";
        ElMessage.success('图片删除成功');
        handleDeleteImageToOss(imageUrl);
    }).catch(() => {
        // 用户取消删除
    });
}
// 在 script setup 部分添加删除云上图片的函数
function handleDeleteImageToOss(imageUrl) {
    // 调用后端接口删除云上的图片
    // 这里需要你根据实际的API来实现
    fetch(import.meta.env.VITE_APP_BASE_ZS_API + "/AttractInvestment/follow/deleteImage", {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            imageUrl: imageUrl
        })
    })
        .then(response => response.json())
        .then(res => {
            if (res.code == 200) {
                //   ElMessage.success('COS云图片已删除');
            } else {
                ElMessage.error('COS云图片删除失败: ' + (res.msg || '未知错误'));
            }
        })
        .catch(error => {
            console.error('删除COS云图片出错:', error);
            ElMessage.error('COS云图片删除失败');
        });
}
// 上传失败处理
function handleUploadError() {
    proxy.$modal.msgWarning("图片插入失败");
}
// 图片上传↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑


const userStr = useUserStore();
const { username, nickname, gszt, deptId, deptName } = userStr;

const router = useRouter();
//新增跟进记录↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓
// 在 existing code 中添加以下内容
const accompanyingVisitorLoading = ref(false);
const filteredAccompanyingVisitorList = ref([]);

// 初始化时设置过滤列表
onMounted(() => {
    filteredAccompanyingVisitorList.value = accompanyingVisitorList.value;
});

// 过滤陪访人员列表
const filterAccompanyingVisitors = (query) => {
    accompanyingVisitorLoading.value = true;
    if (query) {
        filteredAccompanyingVisitorList.value = accompanyingVisitorList.value.filter(item =>
            item.toLowerCase().includes(query.toLowerCase())
        );
    } else {
        filteredAccompanyingVisitorList.value = accompanyingVisitorList.value;
    }
    accompanyingVisitorLoading.value = false;
};
const addFollowRecodeRules = reactive({
    contactPerson: [{ required: true, message: "请选择联系人姓名",trigger: "blur" }],
    followUpType: [
        { required: true, message: '请选择跟进方式', trigger: 'change' }
    ],
    customerIntentionLevel: [
        { required: true, message: '请选择客户意向等级', trigger: 'change' }
    ],
    investmentTarget: [
        { required: true, message: '请选择客户类型', trigger: 'change' }
    ],
    customerProgress: [
        { required: true, message: '请选择招商阶段', trigger: 'change' }
    ],
    // followUpTime: [
    //   { required: true, message: '请选择跟进时间', trigger: 'change' }
    // ],
    followUpContent: [
        { required: true, message: '请填写跟进记录', trigger: 'blur' },
        { min: 10, message: '跟进记录不能少于10个字', trigger: 'blur' }
    ],
    attachmentUrl: [
        { required: true, message: '请上传打卡图片', trigger: 'blur' }
    ]
});
const dialogAddFollowUpVisible = ref(false);
// 日期选项 - 只能选择当天及以后（根据需求调整）
const followDateOptions = reactive({
    disabledDate: (time) => {
        // 如果只能选择当天，使用这个：
        const today = new Date();
        today.setHours(0, 0, 0, 0);
        return time.getTime() < today.getTime();

        // 如果可以选择当天及以后，使用这个：
        // const today = new Date();
        // today.setHours(0, 0, 0, 0);
        // return time.getTime() < today.getTime();
    },
});
const followDateOptions1 = reactive({
    disabledDate1: (time) => {
        // 如果只能选择当天，使用这个：
        const today = new Date();
        today.setHours(0, 0, 0, 0);
        return time.getTime() > today.getTime();

        // 如果可以选择当天及以后，使用这个：
        // const today = new Date();
        // today.setHours(0, 0, 0, 0);
        // return time.getTime() < today.getTime();
    },
});
// 处理日期变化
const handleDateChange = (date) => {
    // 如果需要，可以在这里处理日期变化逻辑
    console.log("选择的日期:", date);
};

// 修改 formDataAddFollow 数据结构
/**
 * company_name
 accompany_staff
 招商对象企业 investment_target
 contact_person
 follow_up_type
 客户意向等级 customer_intention_level
 招商对象 customer_source
 招商阶段customer_progress
 跟进时间follow_up_time
 跟进记录follow_up_content
 下次跟进时间 auto_create_time */
const formDataAddFollow = reactive({
    companyName: '',
    accompanyStaff: '',
    investmentTarget: '',
    contactPerson: '',
    followUpType: '',
    customerIntentionLevel: '',
//   customerSource: '',
    customerProgress: '',
//   followUpTime: new Date().toLocaleDateString(),
    followUpContent: '',
    replyTime: '',
    //创建人creator_name 项目名department 招商员investment_staff  商户编号customer_code
    creatorName: '',
    department: '',
    investmentStaff: '',
    customerCode: '',
    attachmentUrl: '', // 添加图片URL字段
    followUpDate: new Date(), // 新增日期字段，默认当天
    followUpDate1: new Date(), // 新增日期字段，默认当天
    followUpTime: "" ,// 时间字段

});
// 新增渠道 - 使用弹窗方式
function handleAddFollowUp() {
    formDataAddFollow.companyName = currentCompany.companyName || '';
    formDataAddFollow.creatorName = username || '';
    formDataAddFollow.department = deptName || '';
    formDataAddFollow.investmentStaff = nickname || '';
    formDataAddFollow.customerCode = currentCompany.customerId || '';
    formDataAddFollow.followUpDate = new Date();
    formDataAddFollow.followUpTime = "";
    dialogAddFollowUpVisible.value = true;
    fetchContactList();
    fetchAccompanyingVisitorList();
}
// 表单引用
const formRefFollowUp = ref(null);
// 提交表单
// 修改 handleSubmitFollowUp 函数
function handleSubmitFollowUp() {
    formRefFollowUp.value.validate((valid) => {
        if (valid) {
            // 处理 accompanyStaff 数据，如果是数组则转换为字符串
            let accompanyStaffValue = formDataAddFollow.accompanyStaff;
            if (Array.isArray(accompanyStaffValue)) {
                accompanyStaffValue = accompanyStaffValue.join(",");
            }

            // 组合日期和时间
            let combinedDateTime = "";
            if (formDataAddFollow.followUpDate) {
                const datePart = new Date(formDataAddFollow.followUpDate);
                const year = datePart.getFullYear();
                const month = String(datePart.getMonth() + 1).padStart(2, "0");
                const day = String(datePart.getDate()).padStart(2, "0");

                // 如果有选择时间，使用选择的时间，否则使用当前时间
                const timePart = formDataAddFollow.followUpTime ||
                    new Date().toTimeString().slice(0, 8);

                combinedDateTime = `${year}-${month}-${day} ${timePart}`;
            } else {
                // 如果没有选择日期，使用当前日期和时间
                const now = new Date();
                const year = now.getFullYear();
                const month = String(now.getMonth() + 1).padStart(2, "0");
                const day = String(now.getDate()).padStart(2, "0");
                const timePart = formDataAddFollow.followUpTime ||
                    now.toTimeString().slice(0, 8);

                combinedDateTime = `${year}-${month}-${day} ${timePart}`;
            }

            // 创建提交数据
            const submitData = {
                ...formDataAddFollow,
                accompanyStaff: accompanyStaffValue,
                followUpTime: combinedDateTime,
            };

            // 移除不需要提交的临时字段
            delete submitData.followUpDate;

            // 调用 API 创建渠道
            console.log("提交数据:", submitData);
            addFollowRecord(submitData)
                .then((res) => {
                    if (res.code === 200) {
                        ElMessage.success("新增成功");
                        dialogAddFollowUpVisible.value = false;
                        // // 刷新列表
                        handleCloseFollowUp();
                        refreshDrawerContent();
                    } else {
                        proxy.$modal.msgError(res.msg || "新增失败");
                    }
                }).catch(error => {
                console.error("新增渠道失败:", error);
            });
        }
    });
}
// 新增函数：刷新抽屉内容
// 当前的 refreshDrawerContent 函数
function refreshDrawerContent() {
    if (currentCompany.customerId) {
        // 刷新客户基本信息
        selectCustomerListByCustomerId(currentCompany.customerId)
            .then(res => {
                if (res.code === 200 && res.data) {
                    Object.assign(currentCompany, res.data);
                }
            })
            .catch(err => {
                console.error('刷新客户详情失败:', err);
            });

        // 刷新跟进记录
        getFollowList();

        // 刷新客户需求
        getCustomerRequirementList();
    }
}
// 限制只能选择当前时间之前的时间（包括今天）

// 在组件挂载时检查配置
const pickerOptions = reactive({
    disabledDate: (time) => {
        console.log('disabledDate 被调用', time);
        const today = new Date();
        today.setHours(0, 0, 0, 0);

        const tomorrow = new Date(today);
        tomorrow.setDate(tomorrow.getDate() + 1);

        return time.getTime() < today.getTime() || time.getTime() >= tomorrow.getTime();
    }
});
// 关闭弹窗
function handleCloseFollowUp() {
    dialogAddFollowUpVisible.value = false;
    formDataAddFollow.attachmentUrl = "";
    formDataAddFollow.companyName= "";
    formDataAddFollow.accompanyStaff= "";
    formDataAddFollow.investmentTarget= "";
    formDataAddFollow.contactPerson= "";
    formDataAddFollow.followUpType= "";
    formDataAddFollow.customerIntentionLevel= "";
    formDataAddFollow.customerSource= "";
    formDataAddFollow.customerProgress= "";
    formDataAddFollow.followUpContent= "";
    formDataAddFollow.replyTime= "";
    formDataAddFollow.creatorName= "";
    formDataAddFollow.department= "";
    formDataAddFollow.investmentStaff= "";
    formDataAddFollow.customerCode= "";
}
// 新增渠道 - 查询陪访人员
// 新增渠道 - 查询陪访人员
// 新增渠道 - 查询联系人
// 添加获取联系人列表的函数
const AddFollowContactList = ref([]); // 用于存储联系人列表
const fetchContactList = async () => {
    try {

        const res = await getContactListByCustomerCode(currentCompany.customerId);
        if (res && res.code === 200) {
            // 假设后端返回的数据结构为 { code: 200, data: ['联系人1', '联系人2', ...] }
            AddFollowContactList.value = Array.isArray(res.data) ? res.data : [];
        } else {
            AddFollowContactList.value = [];
        }
    } catch (error) {
        console.error("获取联系人列表失败:", error);
        AddFollowContactList.value = [];
    }
};
// 陪访人员列表
const accompanyingVisitorList = ref([]);

// 获取陪访人员列表
const fetchAccompanyingVisitorList = async () => {
    try {
        const params = {
            username: username,
            nickname: nickname
        };
        const res = await getAccompanyingVisitorListAll(params);
        if (res && res.code === 200) {
            accompanyingVisitorList.value = Array.isArray(res.data) ? res.data : [];
        } else {
            accompanyingVisitorList.value = [];
        }
    } catch (error) {
        console.error("获取陪访人员列表失败:", error);
        accompanyingVisitorList.value = [];
    }
};
//新增跟进记录↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑

// 客户类型选项
const customerTypeOptions = ref([
    {
        label: '企业客户',
        value: '企业客户'
    },
    {
        label: '招商渠道',
        value: '招商渠道',
        children: [
            { label: '政府部门', value: '政府部门' },
            { label: '商会协会', value: '商会协会' },
            { label: '同行载体', value: '同行载体' },
            { label: '中介服务', value: '中介服务' },
            { label: '财税服务', value: '财税服务' },
            { label: '法律服务', value: '法律服务' }
        ]
    }
]);

// 级联选择器属性
const cascaderProps = reactive({
    multiple: true,
    emitPath: false,
    checkStrictly: true
});

// 处理客户类型变化
const handleCustomerTypeChange = (value) => {
    console.log('客户类型选择变化:', value);
    // 这里可以根据需要添加额外的处理逻辑
};
// 抽屉状态
const drawerVisible = ref(false);
const contactDrawerVisible = ref(false);

// 当前公司数据
const currentCompany = reactive({
    department: '',
    companyName: '',
    estimatedTax: '',
    reportTime: '',
    investmentTarget: '',
    estimatedAchievementTime: '',
    businessDeveloper: '',
    id: '',
    industry: '',
    customerId: ''
});

// 打开抽屉
const openDrawer = (company) => {
    console.log('传入的company数据:', company);
    Object.assign(currentCompany, company);
    console.log('currentCompany数据:', currentCompany);
    // 调用 selectCustomerListByCustomerId 获取详细信息
    if (company.customerId) {
        selectCustomerListByCustomerId(company.customerId)
            .then(res => {
                if (res.code === 200 && res.data) {
                    // 更新 currentCompany 数据
                    Object.assign(currentCompany, res.data);
                }
            })
            .catch(err => {
                console.error('获取客户详情失败:', err);
                ElMessage.error('获取客户详情失败');
            });
    }
    drawerVisible.value = true;
    // 加载跟进记录
    getFollowList();
    // 获取客户需求列表
    getCustomerRequirementList();
};

// 关闭抽屉
const handleClose = () => {
    drawerVisible.value = false;
};

// 刷新数据
const refreshData = () => {
    console.log('刷新数据');
};

// 联系人列表数据
const contactList = ref([]);

// 联系人维护
const handleContactManage = () => {
    const customerId = currentCompany.customerId;
    console.log('customerId:', customerId);
    if (!customerId) {
        ElMessage.error('无法获取客户ID');
        return;
    }

    getCustomerContact(customerId)
        .then(res => {
            if (res.code === 200 && Array.isArray(res.data)) {
                // 为每个联系人添加 expanded 属性，默认为 false
                contactList.value = res.data.map(contact => ({
                    ...contact,
                    expanded: false
                }));
            } else {
                contactList.value = [];
            }
            contactDrawerVisible.value = true;
        })
        .catch(err => {
            console.error('获取联系人失败:', err);
            ElMessage.error('获取联系人失败');
        });
};

// 添加展开/折叠函数
const toggleContactDetail = (index) => {
    // 切换当前联系人的展开状态
    contactList.value[index].expanded = !contactList.value[index].expanded;
};


// 关闭联系人抽屉
const handleCloseContactDrawer = () => {
    contactDrawerVisible.value = false;
    contactList.value = [];
};




// 重新分配跟进人员相关
const reassignDialogVisible = ref(false);
const reassignForm = reactive({
    customerId: '',
    companyName: '',
    originalBusinessDeveloper: '',
    originalTimeRange: '',
    newStartTime: '',
    department: '',
    newBusinessDeveloper: ''
});

const reassignFormRef = ref(null);
const reassignRules = reactive({
    newStartTime: [
        { required: true, message: '请选择新开始时间', trigger: 'change' }
    ],
    newBusinessDeveloper: [
        { required: true, message: '请选择新跟进招商员', trigger: 'change' }
    ]
});

// 日期选项 - 不能选择今天及之前的时间，默认明天
const reassignDateOptions = reactive({
    disabledDate: (time) => {
        const today = new Date();
        today.setHours(0, 0, 0, 0);
        return time.getTime() <= today.getTime();
    }
});

// 部门列表和招商员列表
const reassignDepartmentList = ref([]);
const reassignDepartmentLoading = ref(false);
const reassignBusinessDeveloperList = ref([]);
const reassignBusinessDeveloperLoading = ref(false);

// 获取部门列表
const fetchReassignDepartmentList = async () => {
    reassignDepartmentLoading.value = true;
    try {
        const res = await getDepartmentList();
        if (res && res.code === 200) {
            let rawData = [];
            if (Array.isArray(res.data)) {
                rawData = res.data;
            } else if (
                res.data &&
                typeof res.data === "object" &&
                typeof res.data.length === "number"
            ) {
                rawData = Array.from(res.data);
            }
            // 过滤掉空字符串和"undefined"字符串
            reassignDepartmentList.value = rawData.filter(item => 
                item !== "" && item !== "undefined" && item != null
            );
        } else {
            reassignDepartmentList.value = [];
        }
    } catch (error) {
        console.error("获取部门列表失败:", error);
        reassignDepartmentList.value = [];
    } finally {
        reassignDepartmentLoading.value = false;
    }
};

// 根据部门获取招商员列表
const fetchReassignBusinessDevelopers = async (intentionProject) => {
    if (!intentionProject) {
        reassignBusinessDeveloperList.value = [];
        return;
    }
    reassignBusinessDeveloperLoading.value = true;
    try {
        const res = await getBusinessDevelopers({ intentionProject });
        if (res && res.code === 200) {
            reassignBusinessDeveloperList.value = Array.isArray(res.data) 
                ? res.data 
                : [];
        } else {
            reassignBusinessDeveloperList.value = [];
        }
    } catch (error) {
        console.error("获取招商员列表失败:", error);
        reassignBusinessDeveloperList.value = [];
    } finally {
        reassignBusinessDeveloperLoading.value = false;
    }
};

// 部门变化时重新获取招商员列表
const handleReassignDepartmentChange = (department) => {
    reassignForm.newBusinessDeveloper = '';
    fetchReassignBusinessDevelopers(department);
};

// 格式化日期为 YYYY/MM/DD
const formatDateForDisplay = (dateStr) => {
    if (!dateStr) return '';
    try {
        const date = new Date(dateStr);
        // 检查日期是否有效
        if (isNaN(date.getTime())) {
            return '';
        }
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}/${month}/${day}`;
    } catch (error) {
        console.error('日期格式化失败:', error, dateStr);
        return '';
    }
};

// 打开重新分配弹窗
const handleReassign = async () => {
    if (!currentCompany.customerId) {
        ElMessage.error('无法获取客户信息');
        return;
    }

    // 重置表单
    resetReassignForm();

    // 填充基本信息
    reassignForm.customerId = currentCompany.customerId;
    reassignForm.companyName = currentCompany.companyName || '';
    reassignForm.originalBusinessDeveloper = currentCompany.businessDeveloper || '';

    // 处理原招商时间：报备时间 至 预计达成时间
    const reportTime = currentCompany.reportTime ? formatDateForDisplay(currentCompany.reportTime) : '';
    const estimatedTime = currentCompany.estimatedAchievementTime 
        ? formatDateForDisplay(currentCompany.estimatedAchievementTime) 
        : '';
    
    if (reportTime && estimatedTime) {
        reassignForm.originalTimeRange = `${reportTime} 至 ${estimatedTime}`;
    } else if (reportTime) {
        reassignForm.originalTimeRange = reportTime;
    } else {
        reassignForm.originalTimeRange = '-';
    }

    // 设置默认新开始时间为明天
    const tomorrow = new Date();
    tomorrow.setDate(tomorrow.getDate() + 1);
    tomorrow.setHours(0, 0, 0, 0);
    const year = tomorrow.getFullYear();
    const month = String(tomorrow.getMonth() + 1).padStart(2, '0');
    const day = String(tomorrow.getDate()).padStart(2, '0');
    reassignForm.newStartTime = `${year}-${month}-${day}`;

    // 获取部门列表
    await fetchReassignDepartmentList();
    
    // 设置默认部门为当前登录用户的部门
    if (deptName) {
        reassignForm.department = deptName;
        // 获取该部门的招商员列表
        await fetchReassignBusinessDevelopers(deptName);
        // 设置默认招商员为当前登录用户
        if (nickname) {
            // 如果当前用户不在列表中，将其添加到列表中
            if (!reassignBusinessDeveloperList.value.includes(nickname)) {
                reassignBusinessDeveloperList.value.push(nickname);
            }
            reassignForm.newBusinessDeveloper = nickname;
        }
    }

    reassignDialogVisible.value = true;
};

// 关闭重新分配弹窗
const handleCloseReassignDialog = () => {
    ElMessageBox.confirm('确认放弃修改吗？')
        .then(() => {
            reassignDialogVisible.value = false;
            resetReassignForm();
        })
        .catch(() => {
            // 用户取消操作
        });
};

// 重置重新分配表单
function resetReassignForm() {
    reassignFormRef.value?.resetFields();
    reassignForm.customerId = '';
    reassignForm.companyName = '';
    reassignForm.originalBusinessDeveloper = '';
    reassignForm.originalTimeRange = '';
    reassignForm.newStartTime = '';
    reassignForm.department = '';
    reassignForm.newBusinessDeveloper = '';
    reassignBusinessDeveloperList.value = [];
}

// 提交重新分配表单
function submitReassignForm() {
    reassignFormRef.value.validate(valid => {
        if (valid) {
            const submitData = {
                customerId: reassignForm.customerId,
                reportTime: reassignForm.newStartTime, // 新开始时间修改报备时间
                department: reassignForm.department,
                businessDeveloper: reassignForm.newBusinessDeveloper
            };

            updateBusinessDeveloperByCustomerId(submitData)
                .then(res => {
                    if (res.code === 200) {
                        ElMessage.success('重新分配成功');
                        reassignDialogVisible.value = false;
                        resetReassignForm();
                        // 刷新列表和抽屉内容
                        getList();
                        refreshDrawerContent();
                    } else {
                        ElMessage.error(res.msg || '重新分配失败');
                    }
                })
                .catch(err => {
                    console.error('重新分配失败:', err);
                    ElMessage.error('重新分配失败');
                });
        } else {
            ElMessage.error('请检查输入内容');
        }
    });
}


const handleReportDifficulty = () => {
    console.log('招商难点提报');
};

// 放弃原因弹窗相关
const abandonDialogVisible = ref(false);
const abandonForm = reactive({
    abandonReason: ''
});
const abandonFormRef = ref(null);
const abandonRules = reactive({
    abandonReason: [
        { required: true, message: '请输入退回原因', trigger: 'blur' }
    ]
});

// 修改 handleAbandon 函数
const handleAbandon = () => {
    const customerId = currentCompany.customerId;
    if (!customerId) {
        ElMessage.error('无法获取客户ID');
        return;
    }

    // 打开放弃原因弹窗
    abandonDialogVisible.value = true;
};

// 关闭放弃弹窗
const handleCloseAbandonDialog = () => {
    abandonDialogVisible.value = false;
    resetAbandonForm();
};

// 重置放弃表单
function resetAbandonForm() {
    abandonFormRef.value?.resetFields();
    abandonForm.abandonReason = '';
}

// 提交放弃表单
function submitAbandonForm() {
    abandonFormRef.value?.validate((valid) => {
        if (valid) {
            ElMessageBox.confirm(
                '确定要将该客户放入公海池吗？',
                '确认放入',
                {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }
            ).then(() => {
                // 在这里传递放弃原因到后端
                const params = {
                    customerId: currentCompany.customerId,
                    abandonReason: abandonForm.abandonReason
                };

                updateScoreA(params)
                    .then(response => {
                        if (response.code === 200) {
                            ElMessage.success('操作成功');
                            abandonDialogVisible.value = false;
                            resetAbandonForm();
                            drawerVisible.value = false;
                            getList(); // 重新加载列表
                        } else {
                            ElMessage.error(response.msg || '操作失败');
                        }
                    })
                    .catch(error => {
                        console.error('放弃客户失败:', error);
                        ElMessage.error('操作失败');
                    });
            }).catch(() => {
                // 用户取消操作
            });
        }
    });
}


// 打开弹窗
const openReportDialog = () => {
    // 可以初始化默认值
    reportForm.companyName = currentCompany.companyName || '';
    reportForm.entryMode = '实体';
    reportForm.authorizedEntity = '我方代办';
    reportForm.area = '';
    reportForm.zt = '';
    reportForm.roomNum = '';

    reportDialogVisible.value = true;
};

const reportFormRef = ref(null);

const submitReportForm = () => {
    reportFormRef.value.validate((valid) => {
        if (valid) {
            // 构造提交数据，包含 customerId
            const submitData = {
                ...reportForm,
                companyId: currentCompany.customerId, // 添加客户ID
                industryCategory:currentCompany.industry,
                merchants :currentCompany.businessDeveloper,
                companyClass:"新注册"
            };

            // 调用 API 提交数据
            insertCompanyTotal(submitData)
                .then(res => {
                    if (res.code === 200) {
                        ElMessage.success('提报成功');
                        reportDialogVisible.value = false;
                        resetReportForm(); // 可选：重置表单
                        getList(); // 可选：刷新列表
                    } else {
                        ElMessage.error(res.msg || '提报失败');
                    }
                })
                .catch(error => {
                    console.error('提报失败:', error);
                    // ElMessage.error('提交失败，请检查网络或联系管理员');
                });
        }
    });
};
function resetReportForm() {
    reportForm.companyName = '';
    reportForm.entryMode = '实体';
    reportForm.zt = '';
    reportForm.authorizedEntity = '我方代办';
    reportForm.roomNum = '';
    reportForm.area = '';
}
const handleCloseReportDialog = () => {
    reportFormRef.value?.resetFields();
    reportDialogVisible.value = false;
};

// 迁址办证弹窗控制
const relocationDialogVisible = ref(false);

// 迁址办证表单数据
const relocationForm = reactive({
    companyName: '', // 目标客户
    entryMode: '实体', // 入住类型，默认值
    zt: '', // 入驻项目
    authorizedEntity: '我方代办', // 核办主体
    roomNum: '', // 新注册地址
    area: '' // 面积
});

const relocationFormRef = ref(null);

const relocationRules = reactive({
    companyName: [
        { required: true, message: '请输入目标客户名称', trigger: 'blur' }
    ],
    zt: [
        { required: true, message: '请选择入驻项目', trigger: 'change' }
    ],
    roomNum: [
        { required: true, message: '请输入具体房间号或工位', trigger: 'blur' }
    ],
    area: [
        { required: true, message: '请输入面积', trigger: 'blur' },
        { type: 'number', message: '面积必须为数字', trigger: 'blur' }
    ]
});

// 打开迁址办证弹窗
const handleRelocation = () => {
    // 初始化默认值
    relocationForm.companyName = currentCompany.companyName || '';
    relocationForm.entryMode = '实体';
    relocationForm.authorizedEntity = '我方代办';
    relocationForm.area = '';
    relocationForm.zt = '';
    relocationForm.roomNum = '';

    relocationDialogVisible.value = true;
};

// 提交迁址办证表单
const submitRelocationForm = () => {
    relocationFormRef.value.validate((valid) => {
        if (valid) {
            // 构造提交数据，包含 customerId
            const submitData = {
                ...relocationForm,
                companyId: currentCompany.customerId, // 添加客户ID
                industryCategory: currentCompany.industry,
                merchants: currentCompany.businessDeveloper,
                companyClass: "迁址"
            };

            // 调用 API 提交数据
            insertCompanyTotal(submitData)
                .then(res => {
                    if (res.code === 200) {
                        ElMessage.success('提报成功');
                        relocationDialogVisible.value = false;
                        resetRelocationForm(); // 重置表单
                        getList(); // 刷新列表
                    } else {
                        ElMessage.error(res.msg || '提报失败');
                    }
                })
                .catch(error => {
                    console.error('提报失败:', error);
                    // ElMessage.error('提交失败，请检查网络或联系管理员');
                });
        }
    });
};

// 重置迁址办证表单
function resetRelocationForm() {
    relocationForm.companyName = '';
    relocationForm.entryMode = '实体';
    relocationForm.zt = '';
    relocationForm.authorizedEntity = '我方代办';
    relocationForm.roomNum = '';
    relocationForm.area = '';
}

// 关闭迁址办证弹窗
const handleCloseRelocationDialog = () => {
    relocationFormRef.value?.resetFields();
    relocationDialogVisible.value = false;
};

// 数据列表相关
const loading = ref(false);
const total = ref(0);
const customerList = ref([]);
const dateRange = ref([]);

const queryParams = reactive({
    pageNum: 1,
    pageSize: 10,
    businessDeveloper: [],
    contactPhone: "",
    department: "",
    intentionProject: [],
    startDate: "",
    endDate: "",
    investmentTarget: [],  // 一级客户类型，修改为数组类型
    category: [],          // 二级客户类型，修改为数组类型
    investmentTargetValue: [], // 级联选择器绑定的值
});

// 基本信息维护弹窗
const infoDialogVisible = ref(false);
const infoForm = reactive({
    companyName: '',
    contactPerson: '',
    contactPhone: '',
    intentionProject: '',
    customerIntentionLevel: '',
    customerSource: '',
    customerSourceDesc: '',
    investmentPurpose: '',
    industry: '',
    resourceCapability: '',
    checkInType: '',
    enterpriseQualification: '',
    employeeCount: '',
    annualSales: '',
    annualTax: '',
    estimatedAchievementTime: '',
    mainBusiness: '',
    focusPoint: '',
    requirementDesc: '',
    enterpriseAddress: [] // 新增字段
});

const infoRules = reactive({
    // contactPhone: [
    //     { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
    // ]
    companyName: [
        { required: true, message: '请输入客户名称', trigger: 'blur' },
        { pattern: /^\S+$/, message: '企业名称不能包含空格', trigger: 'blur' },
        { min: 1, max: 20, message: '企业名称长度不能超过20个字', trigger: 'blur' }
    ],
});

const infoFormRef = ref(null);

// 基本信息维护
const handleInfoManage = (row) => {
    // 从行数据中获取customerId
    const customerId = row?.customerId;
    console.log('当前选中的行数据：', row);
    console.log('修改基本信息维护', customerId);

    if (!customerId) {
        ElMessage.error('无法获取客户编码');
        return;
    }

    // 更新currentCompany数据
    Object.assign(currentCompany, row);

    selectCustomerListByCustomerId(customerId)
        .then(res => {
            if (res.code === 200 && res.data) {
                // 创建数据副本
                const data = { ...res.data };

                // 将数字转换为客户意向等级选项值
                if (data.customerIntentionLevel) {
                    const levelMap = {
                        '4': 'A级 (已缴纳意向金)',
                        '3': 'B级 (1个月内可签约)',
                        '2': 'C级 (3个月内需持续培育)',
                        '1': 'D级 (明确表示无意向)'
                    };
                    data.customerIntentionLevel = levelMap[data.customerIntentionLevel] || data.customerIntentionLevel;
                }
                // 处理地区数据回显 - 修复这部分代码
                if (data.enterpriseProvince || data.enterpriseCity || data.enterpriseDistrict) {
                    // 根据省市区名称查找对应的编码
                    const addressCodes = [];

                    // 查找省编码
                    if (data.enterpriseProvince) {
                        const provinceItem = processedRegionData.find(province =>
                            province.label.includes(data.enterpriseProvince) ||
                            data.enterpriseProvince.includes(province.label)
                        );
                        if (provinceItem) {
                            addressCodes.push(provinceItem.value);

                            // 查找市编码
                            if (data.enterpriseCity) {
                                const cityItem = (provinceItem.children || []).find(city =>
                                    city.label.includes(data.enterpriseCity) ||
                                    data.enterpriseCity.includes(city.label)
                                );
                                if (cityItem) {
                                    addressCodes.push(cityItem.value);

                                    // 查找区编码
                                    if (data.enterpriseDistrict) {
                                        const districtItem = (cityItem.children || []).find(district =>
                                            district.label.includes(data.enterpriseDistrict) ||
                                            data.enterpriseDistrict.includes(district.label)
                                        );
                                        if (districtItem) {
                                            addressCodes.push(districtItem.value);
                                        }
                                    }
                                }
                            }
                        }
                    }
                    data.enterpriseAddress = addressCodes;
                } else {
                    data.enterpriseAddress = [];
                }
                Object.assign(infoForm, data);
                infoDialogVisible.value = true;
            } else {
                ElMessage.error('获取客户信息失败');
            }
        })
        .catch(err => {
            console.error('获取客户信息失败:', err);
            ElMessage.error('获取客户信息失败');
        });
};

// 关闭基本信息弹窗
const handleInfoDialogClose = () => {
    ElMessageBox.confirm('确认放弃修改吗？')
        .then(() => {
            infoDialogVisible.value = false;
            resetInfoForm();
        })
        .catch(() => {
            // 用户取消操作
        });
};

// 重置基本信息表单
function resetInfoForm() {
    infoFormRef.value?.resetFields();
    for (let key in infoForm) {
        if (typeof infoForm[key] === 'string') {
            infoForm[key] = '';
        } else if (Array.isArray(infoForm[key])) {
            infoForm[key] = [];
        } else if (typeof infoForm[key] === 'object' && infoForm[key] !== null) {
            infoForm[key] = {};
        }
    }
}
const formatDate = (date) => {
    if (!(date instanceof Date)) return '';

    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};
// 提交基本信息表单
function submitInfoForm() {
    infoFormRef.value.validate(valid => {
        if (valid) {
            const submitData = { ...infoForm };

            if (submitData.estimatedAchievementTime instanceof Date) {
                submitData.estimatedAchievementTime = formatDate(submitData.estimatedAchievementTime);
            }
            // 转换客户意向等级 - 修复转换逻辑
            if (submitData.customerIntentionLevel === 'A级 (已缴纳意向金)') {
                submitData.customerIntentionLevel = 4;
            } else if (submitData.customerIntentionLevel === 'B级 (1个月内可签约)') {
                submitData.customerIntentionLevel = 3;
            } else if (submitData.customerIntentionLevel === 'C级 (3个月内需持续培育)') {
                submitData.customerIntentionLevel = 2;
            } else if (submitData.customerIntentionLevel === 'D级 (明确表示无意向)') {
                submitData.customerIntentionLevel = 1;
            }

            // 处理地址数据 - 将编码转换为名称
            if (submitData.enterpriseAddress && Array.isArray(submitData.enterpriseAddress)) {
                const [provinceCode, cityCode, districtCode] = submitData.enterpriseAddress;

                // 根据编码查找对应的中文名称
                submitData.enterpriseProvince = findRegionName(provinceCode) || '';
                submitData.enterpriseCity = findRegionName(cityCode) || '';
                submitData.enterpriseDistrict = findRegionName(districtCode) || '';
            }
            updateCustomerInfo(submitData)
                .then(res => {
                    if (res.code === 200) {
                        ElMessage.success('保存成功');
                        infoDialogVisible.value = false;
                        resetInfoForm();
                        getList();
                        refreshDrawerContent();
                    } else {
                        ElMessage.error(res.msg || '保存失败');
                    }
                })
                .catch(err => {
                    console.error('保存失败:', err);
                    ElMessage.error('保存失败');
                });
        } else {
            ElMessage.error('请检查输入内容');
        }
    });
}

// 新增客户相关
const addDialogVisible = ref(false);
const addForm = reactive({
    department: '',
    businessDeveloper: '',
    investmentTarget: '',
    companyName: '',
    contactPerson: '',
    contactMethod: 'mobile',
    contactPhone: '',
    contactWx: '',
    customerIntentionLevel: '',
    customerSource: '',
    customerSourceDesc: '',
    // 新增字段
    channelLevel: '',
    attribution: '',
    category: '',
    isSigned: ''
});

// 添加客户类型切换处理函数
const handleInvestmentTargetChange = (value) => {
    // 当切换客户类型时，清空相关字段
    if (value === '企业') {
        // 保留企业相关字段，清除其他字段
        addForm.channelLevel = '';
        addForm.belongDepartment = '';
        addForm.channelCategory = '';
        addForm.isSigned = '';
    } else if (value) {
        // 清除企业相关字段
        addForm.customerIntentionLevel = '';
        addForm.customerSource = '';
        addForm.customerSourceDesc = '';
    }
};

const addFormRef = ref(null);

const addRules = reactive({
    companyName: [
        { required: true, message: '请输入客户名称', trigger: 'blur' },
        { pattern: /^\S+$/, message: '企业名称不能包含空格', trigger: 'blur' },
        { min: 1, max: 20, message: '企业名称长度不能超过20个字', trigger: 'blur' }
    ],
    contactPerson: [
        { required: true, message: '请输入联系人', trigger: 'blur' },
        { min: 1, max: 10, message: '联系人姓名长度不能超过10个字符', trigger: 'blur' },
        { pattern: /^[\u4e00-\u9fa5a-zA-Z]+$/, message: '只能输入汉字和英文', trigger: 'blur' }
    ],
    // 根据选择的联系方式动态验证手机或微信
    contactPhone: [
        {
            validator: (rule, value, callback) => {
                if (addForm.contactMethod === 'mobile') {
                    if (!value) {
                        callback(new Error('请输入手机号码'));
                    } else if (!/^1[3-9]\d{9}$/.test(value)) {
                        callback(new Error('请输入正确的手机号码'));
                    } else {
                        callback();
                    }
                } else {
                    callback();
                }
            },
            trigger: 'blur'
        }
    ],
    contactWx: [
        {
            validator: (rule, value, callback) => {
                if (addForm.contactMethod === 'wechat') {
                    if (!value) {
                        callback(new Error('请输入微信号'));
                    } else {
                        callback();
                    }
                } else {
                    callback();
                }
            },
            trigger: 'blur'
        }
    ],
    // 企业相关字段验证（条件性验证）
    customerIntentionLevel: [
        { required: true, message: '请选择客户意向等级', trigger: 'change' },
    ],
    investmentTarget: [
        { required: true, message: '请选择客户类型', trigger: 'change' },
    ],
    customerSource: [
        { required: true, message: '请选择渠道来源', trigger: 'change' },
    ],
    customerSourceDesc: [
        { required: true, message: '请输入渠道名称', trigger: 'blur' },
    ],
    // 招商渠道相关字段验证（条件性验证）
    channelLevel: [
        {
            validator: (rule, value, callback) => {
                if (addForm.investmentTarget === '招商渠道' && !value) {
                    callback(new Error('请选择渠道级别'));
                } else {
                    callback();
                }
            },
            trigger: "change"
        }
    ],
    attribution: [
        {
            validator: (rule, value, callback) => {
                if (addForm.investmentTarget === '招商渠道' && !value) {
                    callback(new Error('请选择归属部门'));
                } else {
                    callback();
                }
            },
            trigger: "change"
        }
    ],
    category: [
        {
            validator: (rule, value, callback) => {
                if (addForm.investmentTarget === '招商渠道' && !value) {
                    callback(new Error('请选择渠道分类'));
                } else {
                    callback();
                }
            },
            trigger: "change"
        }
    ],
    isSigned: [
        {
            validator: (rule, value, callback) => {
                if (addForm.investmentTarget === '招商渠道' && !value) {
                    callback(new Error('请选择是否签约'));
                } else {
                    callback();
                }
            },
            trigger: "change"
        }
    ]
});

// 打开新增弹窗
const openAddDialog = () => {
    const user = getUserInfo();
    addForm.department = user.department;
    addForm.businessDeveloper = user.name;
    addDialogVisible.value = true;
};

// 获取用户信息
const getUserInfo = () => {
    return {
        name: nickname,
        department: deptName
    };
};

// 关闭新增弹窗
const handleAddDialogClose = () => {
    ElMessageBox.confirm('确认放弃吗？')
        .then(() => {
            addDialogVisible.value = false;
            resetAddForm();
        })
        .catch(() => {});
};

// 重置新增表单
function resetAddForm() {
    addFormRef.value?.resetFields();
    for (let key in addForm) {
        if (typeof addForm[key] === 'string') {
            addForm[key] = '';
        }
    }
}

// 提交新增表单
function submitAddForm() {
    addFormRef.value.validate(valid => {
        if (valid) {
            const submitData = { ...addForm };

            // 根据客户类型处理不同的字段
            if (submitData.investmentTarget === '企业客户') {
                // 移除其他类型客户字段
                delete submitData.channelLevel;
                delete submitData.belongDepartment;
                delete submitData.channelCategory;
                delete submitData.isSigned;
            } else {
                // 移除企业客户字段
                delete submitData.customerIntentionLevel;
                delete submitData.customerSource;
                delete submitData.customerSourceDesc;
            }
            // 转换客户意向等级
            if (submitData.customerIntentionLevel === 'A级 (已缴纳意向金)') {
                submitData.customerIntentionLevel = 4;
            } else if (submitData.customerIntentionLevel === 'B级 (1个月内可签约)') {
                submitData.customerIntentionLevel = 3;
            } else if (submitData.customerIntentionLevel === 'C级 (3个月内需持续培育)') {
                submitData.customerIntentionLevel = 2;
            } else if (submitData.customerIntentionLevel === 'D级 (明确表示无意向)') {
                submitData.customerIntentionLevel = 1;
            }

            addCustomerInfo(submitData)
                .then(res => {
                    if (res.code === 200) {
                        ElMessage.success('新增成功');
                        addDialogVisible.value = false;
                        resetAddForm();
                        getList();
                    } else {
                        ElMessage.warning(res.msg || '新增失败');
                    }
                })
                .catch(err => {
                    console.error('新增失败:', err);
                    // ElMessage.error('新增失败');
                });
        } else {
            ElMessage.error('请检查输入内容');
        }
    });
}

// 获取客户列表
function getList() {
    loading.value = true;
    console.log("queryParams", queryParams);

    getCustomerListPage(queryParams)
        .then(res => {
            const result = res;
            if (result && result.code === 200) {
                let rows = [];
                if (Array.isArray(result.rows)) {
                    rows = result.rows;
                } else if (
                    result.rows &&
                    typeof result.rows === "object" &&
                    typeof result.rows.length === "number"
                ) {
                    rows = Array.from(result.rows);
                }
                customerList.value = rows;
                total.value = result.total || 0;
            } else {
                customerList.value = [];
                total.value = 0;
            }
        })
        .catch(err => {
            console.error("请求出错:", err);
            customerList.value = [];
            total.value = 0;
        })
        .finally(() => {
            loading.value = false;
        });
}

// 搜索
function handleQuery() {
    // 处理客户类型筛选条件
    processCustomerTypeFilter();
    queryParams.pageNum = 1;

    if (dateRange.value && dateRange.value.length === 2) {
        const formatDate = (date) => {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            return `${year}-${month}-${day}`;
        };

        queryParams.startDate = formatDate(dateRange.value[0]);
        queryParams.endDate = formatDate(dateRange.value[1]);
    } else {
        queryParams.startDate = "";
        queryParams.endDate = "";
    }
    // 确保 investmentTarget 和 category 是数组格式
    console.log('搜索参数:', {
        investmentTarget: queryParams.investmentTarget,
        category: queryParams.category,
        investmentTargetValue: queryParams.investmentTargetValue
    });

    getList();

}

// 修改处理客户类型筛选条件的函数
const processCustomerTypeFilter = () => {
    // 重置筛选条件
    queryParams.investmentTarget = [];
    queryParams.category = [];

    if (!queryParams.investmentTargetValue || queryParams.investmentTargetValue.length === 0) {
        return;
    }

    console.log('原始investmentTargetValue:', queryParams.investmentTargetValue);

    // 直接分离一级和二级选项
    queryParams.investmentTargetValue.forEach(item => {
        // 检查是否是一级选项
        const isPrimary = customerTypeOptions.value.some(option =>
            option.value === item
        );

        if (isPrimary) {
            // 一级选项
            queryParams.investmentTarget.push(item);
        } else {
            // 二级选项
            queryParams.category.push(item);
        }
    });

    console.log('处理后结果:', {
        investmentTarget: queryParams.investmentTarget,
        category: queryParams.category
    });
};

// 重置搜索
function resetQuery() {
    queryParams.businessDeveloper = [];
    queryParams.department = "";
    queryParams.contactPhone = "";
    queryParams.intentionProject = [];
    queryParams.investmentTargetValue = []; // 级联选择器值
    queryParams.investmentTarget = []; // 一级选项数组
    queryParams.category = []; // 二级选项数组
    queryParams.pageNum = 1;
    delete queryParams.startDate;
    delete queryParams.endDate;
    dateRange.value = [];
    getList();
}

// 新增联系人弹窗状态
const addContactDialogVisible = ref(false);

// 新增联系人表单数据
const addContactForm = reactive({
    customerId: '',
    companyName: '',
    contactName: '',
    position: '',
    mobile: '',
    wechat: '',
    nativeAddress: [], // 级联选择器值
    nativeProvince: '',
    nativeCity: '',
    nativeDistrict: '',
    relationship: '',
    gender: '',
    education: '',
    graduateSchool: '',
    contactAge: '',
    birthday: '',
    intimacyLevel: '',
    personalHobby: '',
    remark: ''
});

// 新增联系人表单验证规则
const validateContactReachable = (rule, value, callback) => {
    if (!addContactForm.mobile && !addContactForm.wechat) {
        callback(new Error('联系人手机和微信号至少填写一个'));
    } else {
        callback();
    }
};

const validateMobileFormat = (rule, value, callback) => {
    if (value && !/^1[3-9]\d{9}$/.test(value)) {
        callback(new Error('请输入正确的手机号码'));
    } else {
        callback();
    }
};

const addContactRules = reactive({
    contactName: [
        { required: true, message: '请输入联系人姓名', trigger: 'blur' }
    ],
    mobile: [
        { validator: validateMobileFormat, trigger: ['blur', 'change'] },
        { validator: validateContactReachable, trigger: ['blur', 'change'] }
    ],
    wechat: [
        { validator: validateContactReachable, trigger: ['blur', 'change'] }
    ]
});

// 新增联系人表单引用
const addContactFormRef = ref(null);

// 打开新增联系人弹窗
const openAddContactForm = () => {
    // 重置表单
    resetAddContactForm();
    // 设置公司名称
    addContactForm.companyName = currentCompany.companyName;
    addContactForm.customerId = currentCompany.customerId;
    addContactDialogVisible.value = true;
};


// 关闭新增联系人弹窗
const handleAddContactClose = () => {
    ElMessageBox.confirm('确认放弃修改吗？')
        .then(() => {
            addContactDialogVisible.value = false;
            resetAddContactForm();
        })
        .catch(() => {
            // 用户取消操作
        });
};

// 重置新增联系人表单
function resetAddContactForm() {
    addContactFormRef.value?.resetFields();
    for (let key in addContactForm) {
        if (typeof addContactForm[key] === 'string') {
            addContactForm[key] = '';
        } else if (Array.isArray(addContactForm[key])) {
            addContactForm[key] = [];
        } else if (typeof addContactForm[key] === 'object' && addContactForm[key] !== null) {
            addContactForm[key] = {};
        }
    }
}

// 在提交表单前处理地址数据
const processAddressData = (form) => {
    const address = form.nativeAddress;
    if (!address || !Array.isArray(address) || address.length === 0) {
        return;
    }

    // 使用 processedRegionData 查找对应的中文名称
    const provinceName = findRegionName(address[0]);
    const cityName = address.length >= 2 ? findRegionName(address[1]) : '';
    const districtName = address.length >= 3 ? findRegionName(address[2]) : '';

    form.nativeProvince = provinceName || '';
    form.nativeCity = cityName || '';
    form.nativeDistrict = districtName || '';
};

// 根据编码查找对应的中文名称
const findRegionName = (code) => {
    if (!code || !processedRegionData || !Array.isArray(processedRegionData)) {
        return null;
    }

    // 遍历 processedRegionData 找到对应的名称
    const findName = (data, code) => {
        if (!Array.isArray(data)) return null;

        for (const item of data) {
            if (item.value === code) {
                return item.label;
            }
            if (item.children) {
                const result = findName(item.children, code);
                if (result) {
                    return result;
                }
            }
        }
        return null;
    };

    return findName(processedRegionData, code);
};
// 提交新增联系人表单
function submitAddContactForm() {
    addContactFormRef.value.validate(valid => {
        if (valid) {
            processAddressData(addContactForm); // 处理地址数据
            const submitData = { ...addContactForm };

            // 调用API提交联系人信息
            contacetInsert(submitData)
                .then(res => {
                    if (res.code === 200) {
                        ElMessage.success('联系人添加成功');
                        addContactDialogVisible.value = false;
                        resetAddContactForm();
                        // 刷新联系人列表
                        handleContactManage();
                    } else {
                        ElMessage.error(res.msg || '添加失败');
                    }
                })
                .catch(err => {
                    console.error('添加联系人失败:', err);
                    ElMessage.error('添加联系人失败');
                });
        } else {
            ElMessage.error('请检查输入内容');
        }
    });
};

// 编辑联系人弹窗状态
const editContactDialogVisible = ref(false);

// 编辑联系人表单数据（复用新增联系人表单）
const editContactForm = reactive({
    id: '', // 添加联系人ID用于更新
    customerId: '',
    companyName: '',
    contactName: '',
    position: '',
    mobile: '',
    wechat: '',
    nativeAddress: [], // 级联选择器值
    nativeProvince: '',
    nativeCity: '',
    nativeDistrict: '',
    relationship: '',
    gender: '',
    education: '',
    graduateSchool: '',
    contactAge: '',
    birthday: '',
    intimacyLevel: '',
    personalHobby: '',
    remark: ''
});

// 编辑联系人表单引用
const editContactFormRef = ref(null);

// 编辑联系人函数
// 修改 editContact 函数，添加籍贯回显逻辑
const editContact = (contact) => {
    // 重置表单
    resetEditContactForm();

    // 填充联系人数据
    Object.keys(contact).forEach(key => {
        if (key in editContactForm) {
            editContactForm[key] = contact[key];
        }
    });

    // 设置公司名称和客户ID
    editContactForm.companyName = currentCompany.companyName;
    editContactForm.customerId = currentCompany.customerId;

    // 处理籍贯回显逻辑
    if (contact.nativeProvince || contact.nativeCity || contact.nativeDistrict) {
        // 根据省市区名称查找对应的编码并设置到级联选择器中
        const addressCodes = [];

        // 查找省编码
        if (contact.nativeProvince) {
            const provinceItem = processedRegionData.find(province =>
                province.label.includes(contact.nativeProvince) ||
                contact.nativeProvince.includes(province.label)
            );
            if (provinceItem) {
                addressCodes.push(provinceItem.value);

                // 查找市编码
                if (contact.nativeCity) {
                    const cityItem = (provinceItem.children || []).find(city =>
                        city.label.includes(contact.nativeCity) ||
                        contact.nativeCity.includes(city.label)
                    );
                    if (cityItem) {
                        addressCodes.push(cityItem.value);

                        // 查找区编码
                        if (contact.nativeDistrict) {
                            const districtItem = (cityItem.children || []).find(district =>
                                district.label.includes(contact.nativeDistrict) ||
                                contact.nativeDistrict.includes(district.label)
                            );
                            if (districtItem) {
                                addressCodes.push(districtItem.value);
                            }
                        }
                    }
                }
            }
        }
        editContactForm.nativeAddress = addressCodes;
    }
    // 设置公司名称和客户ID
    editContactForm.companyName = currentCompany.companyName;
    editContactForm.customerId = currentCompany.customerId;
    // 打开编辑弹窗
    editContactDialogVisible.value = true;
};


// 关闭编辑联系人弹窗
const handleEditContactClose = () => {
    ElMessageBox.confirm('确认放弃修改吗？')
        .then(() => {
            editContactDialogVisible.value = false;
            resetEditContactForm();
        })
        .catch(() => {
            // 用户取消操作
        });
};

// 重置编辑联系人表单
function resetEditContactForm() {
    editContactFormRef.value?.resetFields();
    for (let key in editContactForm) {
        if (typeof editContactForm[key] === 'string') {
            editContactForm[key] = '';
        } else if (Array.isArray(editContactForm[key])) {
            editContactForm[key] = [];
        } else if (typeof editContactForm[key] === 'object' && editContactForm[key] !== null) {
            editContactForm[key] = {};
        }
    }
}

// 提交编辑联系人表单
function submitEditContactForm() {
    editContactFormRef.value.validate(valid => {
        if (valid) {
            processAddressData(editContactForm); // 处理地址数据
            const submitData = { ...editContactForm };

            // 调用API更新联系人信息
            updateContacetInfo(submitData)
                .then(res => {
                    if (res.code === 200) {
                        ElMessage.success('联系人更新成功');
                        editContactDialogVisible.value = false;
                        resetEditContactForm();
                        // 刷新联系人列表
                        handleContactManage();
                    } else {
                        ElMessage.error(res.msg || '更新失败');
                    }
                })
                .catch(err => {
                    console.error('更新联系人失败:', err);
                    ElMessage.error('更新联系人失败');
                });
        } else {
            ElMessage.error('请检查输入内容');
        }
    });
};
// 编辑联系人表单验证规则
const editContactRules = reactive({
    contactName: [
        { required: true, message: '请输入联系人姓名', trigger: 'blur' }
    ],
    // 添加手机号和微信号至少填写一个的验证规则
    mobile: [
        {
            validator: (rule, value, callback) => {
                // 如果手机号和微信号都为空，则报错
                if (!value && !editContactForm.wechat) {
                    callback(new Error('手机号和微信号至少填写一个'));
                }
                // 如果填写了手机号，验证手机号格式
                else if (value && !/^1[3-9]\d{9}$/.test(value)) {
                    callback(new Error('请输入正确的手机号码'));
                }
                else {
                    callback();
                }
            },
            trigger: 'blur'
        }
    ],
    wechat: [
        {
            validator: (rule, value, callback) => {
                // 如果手机号和微信号都为空，则报错
                if (!value && !editContactForm.mobile) {
                    callback(new Error('手机号和微信号至少填写一个'));
                } else {
                    callback();
                }
            },
            trigger: 'blur'
        }
    ]
});

// 删除联系人方法
const deleteContact = (contactId, index) => {
    ElMessageBox.confirm(
        '确定要删除该联系人吗？',
        '删除确认',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(() => {
        delCustomerContact(contactId).then(response => {
            if (response.code === 200) {
                ElMessage.success('删除成功');
                // 从列表中移除该联系人
                contactList.value.splice(index, 1);
            } else {
                ElMessage.error(response.msg || '删除失败');
            }
        }).catch(error => {
            console.error('删除联系人失败:', error);
            ElMessage.error('删除联系人失败');
        });
    }).catch(() => {
        // 用户取消删除
    });
};
// 客户需求相关数据
const customerRequirements = ref([]);

// 编辑状态和表单数据
const editingForm = ref(false);
const currentRequirementType = ref(''); // 当前编辑的需求类型
const editForm = ref({
    requirementType: '',
    intentionProject: '',
    // 载体需求字段
    requiredArea: '',
    expectedPrice: '',
    requirementReason: '',
    requirementPurpose: '',
    // 政策需求字段
    estimatedTax: '',
    // 通用字段
    requirementDesc: ''
});

// 获取客户需求列表
const getCustomerRequirementList = () => {
    if (!currentCompany.customerId) {
        ElMessage.error('无法获取客户编码');
        return;
    }

    getCustomerRequirementBycustomerId(currentCompany.customerId)
        .then(res => {
            console.log('客户需求接口返回:', res);
            if (res.code === 200 && Array.isArray(res.data)) {
                customerRequirements.value = res.data;
            } else {
                customerRequirements.value = [];
            }
        })
        .catch(err => {
            console.error('获取客户需求失败:', err);
            ElMessage.error('获取客户需求失败');
        });
};

// 添加客户需求的命令处理函数
const handleAddRequirementCommand = (command) => {
    const requirementTypes = {
        carrier: '载体需求',
        policy: '政策需求',
        research: '研发需求',
        tech: '科技申报',
        talent: '人才申报',
        commission: '佣金费用',
        overseas: '出海需求',
        university: '院校合作',
        market: '市场对接',
        finance: '融资需求',
        health: '健康需求'
    };

    // 设置当前编辑的需求类型和表单数据
    currentRequirementType.value = command;
    editForm.value = {
        requirementType: requirementTypes[command],
        intentionProject: '',
        requiredArea: '',
        expectedPrice: '',
        requirementReason: '',
        requirementPurpose: '',
        estimatedTax: '',
        requirementDesc: ''
    };
    editingForm.value = true;
};

// 编辑现有需求
const editRequirement = (index) => {
    const requirement = customerRequirements.value[index];
    editForm.value = { ...requirement };

    // 根据需求类型设置当前编辑类型
    const typeMap = {
        '载体需求': 'carrier',
        '政策需求': 'policy',
        '研发需求': 'research',
        '科技申报': 'tech',
        '人才申报': 'talent',
        '佣金费用': 'commission',
        '出海需求': 'overseas',
        '院校合作': 'university',
        '市场对接': 'market',
        '融资需求': 'finance',
        '健康需求': 'health'
    };

    currentRequirementType.value = typeMap[requirement.requirementType] || '';
    editingForm.value = true;
};

// 保存编辑
const saveEdit = () => {
    // 验证必填字段
    if (!editForm.value.intentionProject) {
        ElMessage.error('请选择意向项目');
        return;
    }

    // 根据需求类型验证特定字段
    if (currentRequirementType.value === 'carrier') {
        if (!editForm.value.requiredArea) {
            ElMessage.error('请选择需求面积');
            return;
        }
    } else if (currentRequirementType.value === 'policy') {
        if (!editForm.value.estimatedTax) {
            ElMessage.error('请输入预计税收');
            return;
        }
    } else {
        if (!editForm.value.requirementDesc) {
            ElMessage.error('请输入需求描述');
            return;
        }
    }

    // 准备提交数据
    const submitData = { ...editForm.value };
    submitData.reportId = currentCompany.id;
    submitData.companyName = currentCompany.companyName;
    submitData.customerId = currentCompany.customerId;

    // 调用API保存需求
    const apiCall = submitData.id ? updateCustomerRequirement : addCustomerRequirement;

    apiCall(submitData)
        .then(res => {
            if (res.code === 200) {
                getCustomerRequirementList();
                editingForm.value = false;
                currentRequirementType.value = '';
                ElMessage.success(submitData.id ? '更新成功' : '添加成功');
            } else {
                ElMessage.error(res.msg || (submitData.id ? '更新失败' : '添加失败'));
            }
        })
        .catch(err => {
            console.error('操作失败:', err);
            ElMessage.error(submitData.id ? '更新失败' : '添加失败');
        });
};

// 取消编辑
const cancelEdit = () => {
    editingForm.value = false;
    currentRequirementType.value = '';
    editForm.value = {
        requirementType: '',
        intentionProject: '',
        requiredArea: '',
        expectedPrice: '',
        requirementReason: '',
        requirementPurpose: '',
        estimatedTax: '',
        requirementDesc: ''
    };
};

// // 删除客户需求
// const deleteRequirement = (index) => {
//     ElMessageBox.confirm(
//         '确定要删除该客户需求吗？',
//         '确认删除',
//         {
//             confirmButtonText: '确定',
//             cancelButtonText: '取消',
//             type: 'warning',
//         }
//     ).then(() => {
//         const requirementId = customerRequirements.value[index].id;
//         deleteCustomerRequirement(requirementId)
//             .then(res => {
//                 if (res.code === 200) {
//                     // 删除成功后，刷新需求列表
//                     getCustomerRequirementList();
//                     ElMessage.success('删除成功');
//                 } else {
//                     ElMessage.error(res.msg || '删除失败');
//                 }
//             })
//             .catch(err => {
//                 console.error('删除需求失败:', err);
//                 ElMessage.error('删除需求失败');
//             });
//     }).catch(() => {
//         // 用户取消操作
//     });
// };


// 新申请弹窗控制
const reportDialogVisible = ref(false);

// 表单数据
const reportForm = reactive({
    companyName: '', // 目标客户
    entryMode: '实体', // 入住类型，默认值
    zt: '', // 入驻项目
    authorizedEntity: '我方代办', // 核办主体
    roomNum: '', // 新注册地址
    area: '' // 面积
});
const reportRules = reactive({
    companyName: [
        { required: true, message: '请输入目标客户名称', trigger: 'blur' }
    ],

    zt: [
        { required: true, message: '请选择入驻项目', trigger: 'change' }
    ],
    roomNum: [
        { required: true, message: '请输入具体房间号或工位', trigger: 'blur' }
    ],
    area: [
        { required: true, message: '请输入面积', trigger: 'blur' },
        { type: 'number', message: '面积必须为数字', trigger: 'blur' }
    ]
});

// 添加相关跟进数据和参数
const followList = ref([]);
const followTotal = ref(0);
const followParams = reactive({
    pageNum: 1,
    pageSize: 5,
    customerId: ''
});

// 获取跟进记录列表
const getFollowList = () => {
    if (!currentCompany.customerId) {
        ElMessage.error('无法获取客户编码');
        return;
    }

    getByCustomerCode(currentCompany.customerId)
        .then(res => {
            console.log('跟进记录接口返回:', res);
            if (res.code === 200 && Array.isArray(res.data)) {
                // 直接赋值，因为接口返回的就是数组
                followList.value = res.data;
                followTotal.value = res.data.length;
            } else {
                followList.value = [];
                followTotal.value = 0;
            }
        })
        .catch(err => {
            console.error('获取跟进记录失败:', err);
            ElMessage.error('获取跟进记录失败');
        })

};

//跳转跟进详情页面
const detailDrawerRef = ref(null);
const followDetail = ref({});
const relatedFollowList = ref([]);
// 查看跟进详情
const viewFollowDetail = async (row) => {
    console.log('点击的followUpId:', row); // 添加调试日志
    if (!row) {
        ElMessage.error('无效的跟进ID');
        return;
    }
    try {
        const res = await getById(row);
        if (res.code === 200) {
            followDetail.value = res.data;
            // 如果有相关跟进数据，也一并设置
            if (res.data.customerFollowUpDOList) {
                relatedFollowList.value = res.data.customerFollowUpDOList;
            }
            // 打开详情抽屉
            detailDrawerRef.value?.open();
        } else {
            ElMessage.error('获取详情失败');
        }
    } catch (error) {
        console.error('获取跟进详情失败:', error);
        ElMessage.error('获取详情失败');
    }
};
const dropdownLoading = ref(false);
// 定义各种下拉框数据
const dropdownData = reactive({
    projectList: [],        // 项目列表 (bigCategory=35)
    intentionProject: [],   //意向项目 (bigCategory=27)
    industryList: [],       // 所属行业 (bigCategory=28)
    customerSourceList: [], // 客户来源 (bigCategory=29)
    investmentPurposeList: [], // 招商目的 (bigCategory=30)
    resourceCapabilityList: [], // 资源能力 (bigCategory=31)
    checkInTypeList: [],    // 入驻形态 (bigCategory=32)
    requirementTypeList: [], // 企业需求类型 (bigCategory=33)
    followUpTypeList: [],   // 跟进方式 (bigCategory=34)
    enterpriseQualificationList: [] // 企业资质 (bigCategory=36)
});
// 下拉框配置映射
const dropdownConfig = {
    projectList: 35,
    intentionProject: 27,
    industryList: 28,
    customerSourceList: 29,
    investmentPurposeList: 30,
    resourceCapabilityList: 31,
    checkInTypeList: 32,
    requirementTypeList: 33,
    followUpTypeList: 34,
    enterpriseQualificationList: 36
};
// 通用获取下拉框数据方法
const getDropdownData = async (bigCategory, dataKey) => {
    try {
        dropdownLoading.value = true;
        const res = await getBaseCodeInfoList({ bigCategory });

        if (res.code === 200 && Array.isArray(res.rows) && res.rows.length > 0) {
            // 使用 content 字段作为 label 和 value
            dropdownData[dataKey] = res.rows.map(item => ({
                label: item.content,
                value: item.content
            }));
        } else {
            dropdownData[dataKey] = [];
            console.warn(`获取${dataKey}数据为空`);
        }
    } catch (error) {
        console.error(`获取${dataKey}数据失败:`, error);
        ElMessage.error(`获取${dataKey}数据失败`);
    } finally {
        dropdownLoading.value = false;
    }
};

// 点击下拉框时加载数据的方法
const handleSelectFocus = (dataKey) => {
    const bigCategory = dropdownConfig[dataKey];
    if (!bigCategory) return;

    // 如果已经加载过数据，不再重复加载
    if (dropdownData[dataKey] && dropdownData[dataKey].length > 0) return;

    getDropdownData(bigCategory, dataKey);
};
//意向等级颜色
const getTagType = (level) => {
    switch (level) {
        case 4: // A级 - 重要
            return 'danger'; // 红色
        case 3: // B级 - 次要
            return 'warning'; // 橙色
        case 2: // C级 - 不是很重要
            return 'success'; // 绿色
        default: // D级 - 不是很重要 (1)
            return 'info'; // 蓝色
    }
};
// 标签切换
const activeTab = ref('0');
const handleTabChange = (tab) => {
    console.log('切换标签:', tab.paneName);
};

onMounted(() => {
    getList();
    
    // 动态设置 tooltip 样式（避免重复添加）
    if (!document.getElementById('custom-tooltip-style')) {
        const style = document.createElement('style');
        style.id = 'custom-tooltip-style';
        style.textContent = `
            .el-tooltip__popper,
            .el-tooltip__popper.is-dark,
            .el-popper.is-dark,
            .el-popper[data-popper-placement] {
                background-color: #ffffff !important;
                color: #000000 !important;
                border: 1px solid #e4e7ed !important;
                box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1) !important;
                width: 300px !important;
                max-width: 300px !important;
                min-width: 300px !important;
                padding: 8px 12px !important;
                word-wrap: break-word !important;
                word-break: break-all !important;
            }
            .el-tooltip__popper .el-tooltip__arrow::before,
            .el-tooltip__popper.is-dark .el-tooltip__arrow::before,
            .el-popper.is-dark .el-tooltip__arrow::before {
                background-color: #ffffff !important;
                border: 1px solid #e4e7ed !important;
            }
            .el-tooltip__popper .el-tooltip__arrow,
            .el-tooltip__popper.is-dark .el-tooltip__arrow,
            .el-popper.is-dark .el-tooltip__arrow {
                border-color: #e4e7ed !important;
            }
            .el-tooltip__popper *,
            .el-tooltip__popper.is-dark *,
            .el-popper.is-dark * {
                color: #000000 !important;
            }
        `;
        document.head.appendChild(style);
    }
});
</script>

<style scoped>
.customer-container {
    padding: 24px 32px 0 32px;
    min-height: 100vh;
}

.filter-card {
    margin-bottom: 12px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
    border: 1px solid #f0f0f0;
}

.filter-form {
    padding: 8px 0 0 0;
}

.list-card {
    margin-top: 18px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
    border: 1px solid #f0f0f0;
}

.el-table {
    border-radius: 8px;
    font-size: 15px;
}

.el-table th {
    color: #333;
    font-weight: 600;
    border-bottom: 1px solid #ebeef5;
}

.el-table td {
    color: #444;
    border-bottom: 1px solid #f0f0f0;
}

.el-button[type="primary"] {
    background: linear-gradient(90deg, #4f8cff 0%, #38c8fa 100%);
    border: none;
    color: #fff;
    border-radius: 6px;
    font-weight: 500;
    box-shadow: 0 2px 8px rgba(32, 159, 240, 0.08);
    transition: background 0.2s;
}

.el-button[type="primary"]:hover {
    background: linear-gradient(90deg, #2563eb 0%, #38c8fa 100%);
}

.el-dialog {
    border-radius: 10px;
    box-shadow: 0 8px 32px 0 rgba(31, 38, 135, 0.15);
}

.el-dialog__header {
    border-radius: 10px 10px 0 0;
    font-size: 18px;
    font-weight: 600;
    color: #2563eb;
}

.el-dialog__body {
    padding: 28px 36px 18px 36px;
    min-height: 180px;
    display: flex;
    flex-direction: column;
    justify-content: center;
}

.info-form {
    margin-top: 0;
}

.el-form-item {
    margin-bottom: 18px;
}

.el-form-item .el-link {
    font-size: 15px;
}

.el-form-item .el-upload {
    margin-top: 0;
}

.el-dialog__footer {
    border-radius: 0 0 10px 10px;
    padding: 12px 32px;
}

.el-upload {
    margin-top: 12px;
}

.el-link {
    font-size: 15px;
}

.el-alert {
    margin-bottom: 8px;
}

/* 抽屉样式 */
.drawer-content {
    padding: 20px;
    height: calc(100vh - 120px);
    overflow-y: auto;
    background-color: white;
}

.company-header {
    margin-bottom: 20px;
    padding: 15px;
    background-color: #f5f7fa;
    border-radius: 8px;
    border: 1px solid #ebeef5;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.company-header h3 {
    margin: 0;
    color: #333;
    font-size: 16px;
    font-weight: 600;
}

.company-info {
    margin-bottom: 20px;
    background-color: #fff;
    border: 1px solid #ebeef5;
    border-radius: 8px;
    padding: 15px;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.basic-info {
    margin: 20px 0;
    background-color: #f5f7fa;
    border-radius: 8px;
    padding: 15px;
}

.info-item {
    display: flex;
    margin-bottom: 10px;
    padding: 5px 0;
    border-bottom: 1px dashed #ebeef5;
}

.info-item:last-child {
    border-bottom: none;
}

.label {
    width: 100px;
    color: #666;
    font-weight: 500;
    padding-right: 10px;
}

.value {
    flex: 1;
    color: #333;
}

.operation-list {
    background-color: #fff;
    border: 1px solid #ebeef5;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.list-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px 20px;
    background-color: #f5f7fa;
    border-bottom: 1px solid #ebeef5;
}

.list-title span {
    font-weight: 600;
    color: #333;
}

.operation-group {
    padding: 15px 20px;
    border-bottom: 1px solid #ebeef5;
}

.group-title {
    font-weight: 600;
    color: #333;
    margin-bottom: 10px;
    padding-left: 5px;
    position: relative;
}

.group-title::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 4px;
    height: 16px;
    background-color: #409eff;
    border-radius: 2px;
}

.operation-buttons {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.operation-buttons .el-button {
    padding: 6px 12px;
    font-size: 14px;
    border-radius: 4px;
    transition: all 0.2s;
    border: 1px solid #dcdfe6;
}

.operation-buttons .el-button:hover {
    background-color: #f5f7fa;
    border-color: #409eff;
    color: #409eff;
}

/* 联系人相关样式 */
.contact-list {
    margin-top: 20px;
}

.contact-item {
    background-color: #fff;
    border: 1px solid #ebeef5;
    border-radius: 8px;
    padding: 15px;
    margin-bottom: 10px;
}

.empty-tip {
    text-align: center;
    color: #999;
    padding: 30px;
}

.add-contact-btn {
    margin-top: 20px;
    text-align: center;
}

.action-buttons {
    margin-top: 10px;
    display: flex;
    gap: 8px;
}
/* 添加跟进表格样式 */
.follow-table-container {
    margin-top: 15px;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
    border: 1px solid #f0f0f0;
}

.follow-table-container .el-table th {
    font-weight: 600;
    color: #fff;
    text-align: center;
}

.follow-table-container .el-table td {
    color: #444;
    text-align: center;
}

.follow-table-container .el-table .el-button {
    color: #409eff;
    font-size: 14px;
}
/*快捷操作样式*/
/* 新增样式 */
.company-info {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 16px;
    margin-bottom: 20px;
}

.info-item {
    display: flex;
    margin-bottom: 8px;
    padding: 5px 0;
    border-bottom: 1px dashed #ebeef5;
}

.info-item:last-child {
    border-bottom: none;
}

.label {
    width: 120px;
    color: #666;
    font-weight: 500;
    padding-right: 10px;
    white-space: nowrap;
}

.value {
    flex: 1;
    color: #333;
    word-break: break-all;
}

/* 优化操作列表样式 */
.operation-list {
    background-color: #fff;
    border: 1px solid #ebeef5;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.list-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px 20px;
    background-color: #f5f7fa;
    border-bottom: 1px solid #ebeef5;
}

.list-title span {
    font-weight: 600;
    color: #333;
}

.operation-group {
    padding: 15px 20px;
    border-bottom: 1px solid #ebeef5;
}

.group-title {
    font-weight: 600;
    color: #333;
    margin-bottom: 10px;
    padding-left: 5px;
    position: relative;
}

.group-title::before {
    content: '';
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 4px;
    height: 16px;
    background-color: #409eff;
    border-radius: 2px;
}

.operation-buttons {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.operation-buttons .el-button {
    padding: 6px 12px;
    font-size: 14px;
    border-radius: 4px;
    transition: all 0.2s;
    border: 1px solid #dcdfe6;
}

.operation-buttons .el-button:hover {
    background-color: #f5f7fa;
    border-color: #409eff;
    color: #409eff;
}


/* 联系人编辑样式 */
.contact-info .info-item {
    display: flex;
    align-items: center;
    padding: 8px 0;
    border-bottom: 1px dashed #e4e7ed;
}

.contact-info .info-item .label {
    width: 100px;
    color: #606266;
    font-size: 14px;
}

.contact-info .info-item .value {
    flex: 1;
    color: #909399;
    font-size: 14px;
}
.contact-header .action-buttons {
    display: flex;
    gap: 10px;
}

.contact-info .info-item .el-button {
    margin-left: 8px;
}
/* 客户需求样式 */
.requirement-container {
    margin-top: 16px;
    padding: 12px;
    background-color: #f9f9f9;
    border-radius: 8px;
    border: 1px solid #e4e7ed;
}

.edit-form-container {
    margin-bottom: 16px;
    padding: 16px;
    background-color: white;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
}

.edit-form {
    margin-bottom: 16px;
}

.form-actions {
    text-align: right;
    margin-top: 16px;
}

.requirement-item {
    margin-bottom: 12px;
    padding: 12px;
    background-color: white;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
}

.requirement-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
    padding-bottom: 8px;
    border-bottom: 1px solid #e4e7ed;
}

.requirement-type {
    display: flex;
    align-items: center;
    gap: 8px;
    font-weight: bold;
    color: #333;
}

.requirement-actions {
    display: flex;
    gap: 8px;
}

.requirement-content {
    padding: 8px 0;
}

.requirement-row {
    display: flex;
    margin-bottom: 6px;
    font-size: 14px;
}

.requirement-row .label {
    width: 100px;
    color: #666;
    font-weight: 500;
}

.requirement-row .value {
    flex: 1;
    color: #333;
}

.empty-tip {
    text-align: center;
    color: #999;
    padding: 30px;
    font-size: 14px;
}

.el-dropdown-link {
    cursor: pointer;
    color: #409EFF;
    display: flex;
    align-items: center;
}
/*意向等级颜色*/
.intention-level-tag {
    font-size: 16px;
    padding: 4px 8px;
}
.status-tag {
    font-size: 16px;
    padding: 5px 8px;
}
/*操作按钮样式*/
.operation-button {
    font-size: 16px;
    padding: 4px 8px;
    border-radius: 4px;
    transition: all 0.3s ease;
}

.operation-button:hover {
    background-color: #0066cc;
    color: white;
    text-decoration: none;
}
/*客户类型样式*/
.channel-options {
    max-height: 200px;
    overflow-y: auto;
}

.channel-option {
    padding: 8px 12px;
    cursor: pointer;
    border-radius: 4px;
    transition: background-color 0.2s;
}

.channel-option:hover {
    background-color: #f5f7fa;
}

.channel-option + .channel-option {
    margin-top: 4px;
}

.ellipsis-cell {
    display: inline-block;
    max-width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    vertical-align: middle;
}
</style>

<style>
/* 自定义表格 tooltip 样式 - 白底黑字，固定宽度 */
/* 使用更具体的选择器覆盖 Element Plus 默认样式 */
.el-table .el-tooltip__popper,
.el-table .el-tooltip__popper.is-dark,
.el-tooltip__popper,
.el-tooltip__popper.is-dark,
.el-popper.is-dark,
.el-popper[data-popper-placement],
.el-popper.is-pure,
.el-popper[role="tooltip"] {
    background-color: #ffffff !important;
    color: #000000 !important;
    border: 1px solid #e4e7ed !important;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1) !important;
    width: 200px !important;
    max-width: 300px !important;
    min-width: 300px !important;
    padding: 8px 12px !important;
    word-wrap: break-word !important;
    word-break: break-all !important;
}

.el-table .el-tooltip__popper .el-tooltip__arrow::before,
.el-table .el-tooltip__popper.is-dark .el-tooltip__arrow::before,
.el-tooltip__popper .el-tooltip__arrow::before,
.el-tooltip__popper.is-dark .el-tooltip__arrow::before,
.el-popper.is-dark .el-tooltip__arrow::before,
.el-popper[data-popper-placement] .el-tooltip__arrow::before {
    background-color: #ffffff !important;
    border: 1px solid #e4e7ed !important;
}

.el-table .el-tooltip__popper .el-tooltip__arrow,
.el-table .el-tooltip__popper.is-dark .el-tooltip__arrow,
.el-tooltip__popper .el-tooltip__arrow,
.el-tooltip__popper.is-dark .el-tooltip__arrow,
.el-popper.is-dark .el-tooltip__arrow,
.el-popper[data-popper-placement] .el-tooltip__arrow {
    border-color: #e4e7ed !important;
}

/* 确保文字颜色为黑色，包括所有子元素 */
.el-table .el-tooltip__popper,
.el-table .el-tooltip__popper.is-dark,
.el-tooltip__popper,
.el-tooltip__popper.is-dark,
.el-popper.is-dark,
.el-popper[data-popper-placement],
.el-table .el-tooltip__popper *,
.el-table .el-tooltip__popper.is-dark *,
.el-tooltip__popper *,
.el-tooltip__popper.is-dark *,
.el-popper.is-dark * {
    color: #000000 !important;
}
</style>